angularjs $ watch无法检测对象

时间:2015-05-12 01:27:52

标签: javascript angularjs prototype

我设置监视$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

1 个答案:

答案 0 :(得分:3)

您可以使用$ 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);
});