问题描述
为什么我不能观看服务中的对象.香港专业教育学院有一个简单的变量工作,但一个对象将无法工作. http://plnkr.co/edit/S4b2g3baS7dwQt3t8XEK?p=preview
Why can't I watch a object in a service.Ive got a simple variable working, but a object wont work.http://plnkr.co/edit/S4b2g3baS7dwQt3t8XEK?p=preview
var app = angular.module('plunker', []);
app.service('test', ['$http', '$rootScope',
function ($http, $rootScope) {
var data = 0;
var obj = {
"data": 0
};
this.add = function(){
obj.data += 1;
console.log('data:', obj);
};
this.getData = function() { return obj; };
}]);
app.controller('TestController', ['$scope', '$rootScope', '$filter', 'test',
function($scope, $rootScope, $filter, test) {
//test controller
$scope.add = function(){
test.add();
};
$scope.test = test;
$scope.$watch('test.getData()', function(newVal){
console.log('data changes into: ', newVal)
});
}]);
推荐答案
您需要将true作为$ watch函数的最后一个参数传递,以使相等性检查为angular.equals.否则,仅检查引用相等性.
You need to pass true as the last parameter of the $watch function so that the equality check is angular.equals. Otherwise only reference equality is checked.
$scope.$watch('test.getData()', function(newVal){
console.log('data changes into: ', newVal)
}, true);
重复的问题: $观看对象
编辑
正如下面提到的,该代码包含一个不好的做法–在$scope
中引用了服务.不必在范围内引用它,因为$watch
还接受getter函数作为第一个参数.干净的解决方案使用此函数按下面的答案中的方式返回监视的数组. $scope.$watch(function() { return test.getData(); } ...
As mentioned bellow, the code includes a bad practice – having a service referenced in $scope
. It is not necessary to reference it in scope, since $watch
also accepts a getter function as first argument. Clean solution uses this function to return the watched array as is in the answer below. $scope.$watch(function() { return test.getData(); } ...
要列出完整的解决方案,您还可以使用$watchCollection
来解决引用相等性检查问题.
To list a complete solution you could also use $watchCollection
instead to solve the reference equality check problem.
这篇关于AngularJS监视服务对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!