我正在为 $scope
对象设置监视,除非整个值发生更改,否则不会触发 $watch
更改事件
示例:
//Some where in .run function i set rootScope and set $watch too.
$rootScope.config = {date:'11/4/2015',moreValues:'etc'};
//setting $watch
$rootScope.$watch('config',function(new,old) {
console.log('config value changed :)',new);
});
//----->Inside Controller----------
//NOw THIS WILL NOT TRIGGER $watch
$rootScope.config.date = 'another day';
//Same as this, it will also not trigger $watch
var temp = $rootScope.config;
temp.date = 'another day';
$rootScope.config = temp;
//YET THIS WILL WORK JUST FINE :) AND WILL TRIGGER $watch
var temp = angular.copy($rootScope.config);
temp.date = 'another day';
$rootScope.config = temp;
有人可以告诉我为什么会出现这种行为吗?有没有更好的方法在对象属性更改时触发 $watch
?
最佳答案
您可以使用 $watchCollection,或将第三个参数传递为 true
$rootScope.$watch('config',function(value,old) {
console.log('config value changed :)',value);
}, true);
或
$rootScope.$watchCollection('config',function(value,old) {
console.log('config value changed :)',value);
});
关于javascript - angularjs $watch 无法检测对象中属性的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30180254/