我可能用错了,但我有一个监视变量的函数,当该变量从 View 中更改时,该函数运行..但是当同级函数更改该变量时,监视不会运行。我是不是编码有误?
scope.$watch (settings.number, function(val){
alert('test');
})
scope.exampleObj = {
exampleFunc : function(){
settings.number += 5;
}
};
所以当我调用 scope.exampleObj.exampleFunc(); scope watch 不应该被调用吗?
最佳答案
将字符串替换为函数或使用 $watchCollection,如下所示:
使用变量:
angular.module('TestApp', [])
.controller('MainCtrl', function($scope){
// Object
var settings = {
number: 1,
foobar: 'Hello World'
};
$scope.$watch(function(){ return settings.number; }, function(newValue, oldValue){
console.log('New value detected in settins.number');
});
$scope.$watchCollection(function(){ return settings; }, function(newValue, oldValue){
console.log('New value detected in settings');
});
});
使用 $scope:
angular.module('TestApp', [])
.controller('MainCtrl', function($scope){
// Object
$scope.settings = {
number: 1,
foobar: 'Hello World'
};
$scope.$watch('settings.number', function(newValue, oldValue){
console.log('New value detected in $scope.settings.number');
});
});
示例:http://jsfiddle.net/Chofoteddy/2SNFG/
*注意:$watchCollection 在 AngularJS 1.1.x 及以上版本中可用。如果您需要观察数组中的多个值或对象中的多个属性,它会非常有用。
关于javascript - Angular JS - 范围观察不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23231392/