angularjs $watch 无法检测到对象中的属性更改

Zal*_*oza 0 javascript prototype angularjs

我正在设置监视$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;
Run Code Online (Sandbox Code Playgroud)

有人能告诉我为什么会出现这种行为吗?有没有更好的方法来触发$watch对象属性的更改?

Aru*_*hny 5

您可以使用 $watchCollection,或将第三个参数传递为 true

$rootScope.$watch('config',function(value,old) {
console.log('config value changed :)',value);
}, true);
Run Code Online (Sandbox Code Playgroud)

或者

$rootScope.$watchCollection('config',function(value,old) {
console.log('config value changed :)',value);
});
Run Code Online (Sandbox Code Playgroud)