[英]$watch's object not triggered when attributes are changed
I have one object: 我有一个对象:
$scope.obj = {bar: 'bar value', foo: 'foo value'};
and I want to to know if bar, foo or both change. 我想知道bar,foo或两者都改变了。
I'm doing this: 我正在这样做:
$scope.$watch('obj', function() { console.log("watching obj") });
and If I change the object's attributes "watching obj" message It never shows. 如果我更改了对象的属性“ watching obj”,则消息永远不会显示。 However, if I watch 'obj.foo'
or 'obj.bar'
I can see the message. 但是,如果我观看'obj.foo'
或'obj.bar'
,则可以看到该消息。 So, the question is: 因此,问题是:
Why the message isn't showing when I watch 'obj'
? 为什么当我观看'obj'
时消息没有显示? and how can I do this? 我该怎么办?
You need to set the objectEquality
argument to true
. 您需要将objectEquality
参数设置为true
。
http://docs.angularjs.org/api/ng .$rootScope.Scope http://docs.angularjs.org/api/ng。$ rootScope.Scope
// $watch(watchExpression, listener, objectEquality) // $ watch(watchExpression,listener,objectEquality)
$scope.$watch('obj', function() {
console.log("watching obj")
}, true);
I will just add to @moderndegree's answer, 我将添加到@moderndegree的答案中,
If the object you want to watch has a few elements ( in this case only two) you can also use 如果您要观看的对象只有几个元素(在这种情况下只有两个),您也可以使用
$scope.$watch('obj.foo+obj.bar', function() {
console.log("changed");
});
Which is more efficient than deep watching. 这比深度监视更有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.