javascript - Angular : Updating controller scope variable through a factory variable

标签 javascript angularjs

我研究了如何正确执行此操作的示例,但它绝对不会在我这边更新。我设置了一个断点以确保它正在更新并通过工厂中的计时器并且它正在正确更新。我不应该使用 $watch 对吧?如果有人能帮我弄清楚发生了什么事,这将有助于缓解我现在的头痛,哈哈,谢谢。

工厂

app.factory('FoundationSystemStatusFactory', ['$timeout', '$q', 'SystemStatusFactory', function ($timeout, $q, SystemStatusFactory) {
var service = {};

service.Count = 0;

service.Ping = 0;

service.PollingTest = function() {
    $timeout(function () {

        SystemStatusFactory.PingIP('www.google.com')
            .then(function (data) {
                service.Ping = data.data;
                service.Count++;
            }, function (data) {
                service.Ping = data.data;
            });

        service.PollingTest();
    }, 2000);
}

return service;

}]);

Controller

 FoundationSystemStatusFactory.PollingTest();

 $scope.ping = FoundationSystemStatusFactory.Ping;  //NOT UPDATING

 $scope.count = FoundationSystemStatusFactory.Count;  //NOT UPDATING

编辑:尝试作为服务,仍然无法使其工作:

var self = this;

self.Count = 0;

self.Ping = 0;

self.PollingTest = function () {
    $timeout(function () {

        SystemStatusFactory.PingIP('www.google.com')
            .then(function (data) {
                self.Ping = data.data;
                self.Count++;
            }, function (data) {
                self.Ping = data.data;
            });

        self.PollingTest();
    }, 2000);
}

最佳答案

不同的方法 - 事件

app.factory('FoundationSystemStatusFactory', ['$rootScope', '$timeout', '$q', 'SystemStatusFactory', function ($rootScope, $timeout, $q, SystemStatusFactory) {
var service = {
 Count: 0
};

service.PollingTest = function() {
    $timeout(function () {
        SystemStatusFactory.PingIP('www.google.com')
            .then(function (data) {
                $rootScope.$broadcast('FoundationSystemStatus:ping', data.data);
                service.Count++;
            }).catch(function (data) {
                $rootScope.$broadcast('FoundationSystemStatus:ping', data.data);
            });

        service.PollingTest();
    }, 2000);
}

return service;

}]);

//On controller...
$scope.$on('FoundationSystemStatus:ping', function(ping){
 $scope.ping = ping;
});

关于javascript - Angular : Updating controller scope variable through a factory variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37951818/

相关文章:

javascript - 使用时区缩写将日期转换为用户偏好时区

javascript - 在 JavaScript 中调用嵌套作用域中的内部函数

javascript - 延迟或等待 3 秒然后删除类(class)

javascript - 是否可以创建一个充当单例的指令?

javascript - ng-click 清除输入中的值

javascript - 将项目添加到模型并刷新第二次 ng-repeat

javascript - 如何在 Vis 中的节点顶部绘制边?

Javascript:window.location.search 不更新?

javascript - AngularJS : ngRepeat in Directive with transcluded content

javascript - 如何从 JavaScript 打开带有目标的链接