角JS - 确定看不更新 [英] 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();不应范围的手表被调用?
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');
});
});
使用$范围:
angular.module('TestApp', [])
.controller('MainCtrl', function($scope){
// Object
$scope.settings = {
number: 1,
foobar: 'Hello World'
};
$scope.$watch('settins.number', function(newValue, oldValue){
console.log('New value detected in $scope.settings.number');
});
});
例如: http://jsfiddle.net/Chofoteddy/2SNFG/
的注意:$ watchCollection是在AngularJS版本1.1.x和以上版本。如果你需要看的对象的数组或多个属性的多个值它可以是非常有用的。见denisonluz.com: http://goo.gl/XC7w31 的
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. See in denisonluz.com: http://goo.gl/XC7w31
这篇关于角JS - 确定看不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!