Rob*_*man 11 service watch angularjs
为什么我不能在服务中观看对象.我有一个简单的变量工作,但一个对象不起作用. 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)
});
}]);
Run Code Online (Sandbox Code Playgroud)
Pie*_*let 19
将整个服务注入范围并不是我想做的事情.
我更愿意看一个返回值的函数:
$scope.$watch(function() { return test.getData(); }, function(newVal) {
/* Do the stuff */
}, true);
Run Code Online (Sandbox Code Playgroud)
kve*_*tis 13
您需要传递true作为$ watch函数的最后一个参数,以便相等性检查是angular.equals.否则,仅检查引用相等性.
$scope.$watch('test.getData()', function(newVal){
console.log('data changes into: ', newVal)
}, true);
Run Code Online (Sandbox Code Playgroud)
重复的问题: $观看一个对象
编辑
如下所述,代码包含一个不好的做法 - 引用了一个服务$scope
.没有必要在范围内引用它,因为$watch
也接受getter函数作为第一个参数.Clean解决方案使用此函数返回观察到的数组,如下面的答案所示.
$scope.$watch(function() { return test.getData(); } ...
要列出完整的解决方案,您也可以使用它$watchCollection
来解决引用相等性检查问题.
归档时间: |
|
查看次数: |
17517 次 |
最近记录: |