我查看了如何正确执行此操作的示例,但它绝对不会更新。我设置了一个断点,以确保它正在更新并通过工厂中的计时器并正确更新。我不应该使用$ 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;
}]);
控制器
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);
}
答案 0 :(得分:2)
另一种方法 - 事件。
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;
});
答案 1 :(得分:1)
您可以使用观察者:
$scope.$watch('FoundationSystemStatusFactory.Ping', function(newValue) {
$scope.ping = newValue;
});
或者你可以使用工厂参考:
$scope.status = FoundationSystemStatusFactory;
$interval(function() {
console.log($scope.status.Ping); // gets updated
});
答案 2 :(得分:0)
好的,经过一些研究,我发现了如何做到这一点。对象被引用为数字而字符串则不被引用。
厂
app.factory('FoundationSystemStatusFactory', ['$timeout', '$q', 'SystemStatusFactory', function ($timeout, $q, SystemStatusFactory) {
var service = {};
service.Data = {
Count: 0,
Ping: 0
}
service.PollingTest = function() {
$timeout(function () {
SystemStatusFactory.PingIP('www.google.com')
.then(function (data) {
service.Data.Ping = data.data;
service.Data.Count++;
}, function (data) {
service.Data.Ping = data.data;
});
service.PollingTest();
}, 2000);
}
return service;
}]);
控制器
app.controller('SystemStatusController', ['$scope', '$rootScope', '$timeout', 'FoundationSystemStatusFactory',
function ($scope, $rootScope, $timeout, FoundationSystemStatusFactory) {
FoundationSystemStatusFactory.PollingTest();
$scope.data = FoundationSystemStatusFactory.Data;
}]);
查看
{{data.Ping}}
{{data.Count}}