Angular JS - Scope Watch 未更新 [英] Angular JS - Scope Watch Not Updating
问题描述
我可能用错了这个,但我有一个函数来监视一个变量,当从视图中更改该变量时,该函数会运行..但是当同级函数更改该变量时,该监视不会运行.我编码有问题吗?
I might be using this wrong, but I have a function that watches a variable and when that variable is changed from the view, the function runs.. but when a sibling function changes that variable the watch doesn't run. Am I coding something wrong?
scope.$watch (settings.number, function(val){
alert('test');
})
scope.exampleObj = {
exampleFunc : function(){
settings.number += 5;
}
};
所以当我调用 scope.exampleObj.exampleFunc();不应该调用 scope watch 吗?
so when I call scope.exampleObj.exampleFunc(); shouldn't scope watch get called?
推荐答案
将字符串替换为函数或使用 $watchCollection,如下所示:
Replace string to a function or use $watchCollection, like this:
使用 var:
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 及更高版本中可用.如果您需要查看数组中的多个值或对象中的多个属性,它会非常有用.
*Note: $watchCollection that is available in AngularJS version 1.1.x and above. It can be really useful if you need to watch multiple values in a array or multiple properties in a object.
这篇关于Angular JS - Scope Watch 未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!