为什么$ scope.$ watch有效,而$ scope.$ watchCollection不起作用? [英] Why does $scope.$watch work but $scope.$watchCollection does not?

查看:23
本文介绍了为什么$ scope.$ watch有效,而$ scope.$ watchCollection不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在需要监视更改以便对其进行某些过滤的数组上使用 $ scope.$ watchCollection()方法.当用户使用复选框和按钮在给定数组中的1个或多个这些对象上切换布尔值时,不会适当地触发$ watch.但是,将object_quality标志设置为true的将 $ watchCollection 更改为 $ scope.$ watch(arr,function(){},true)会导致$ watch工作正好.为什么 $ watchCollection 不自动使用objectEquality来确定是否进行了更改?

I tried using the $scope.$watchCollection() method on an array that I need to watch for changes in order to run some filtering on. When the user uses checkboxes and a button to toggle a boolean value on 1 or more of these objects in the given array, the $watch is not being triggered appropriately. However, changing the $watchCollection to a $scope.$watch(arr, function(){}, true) with objectEquality flag set to true causes the $watch to work just fine. Why would the $watchCollection not automatically use objectEquality to determine if changes were made?

推荐答案

来自 $ scope.$ watchCollection 的"nofollow>官方文档:

From the official documentation of $scope.$watchCollection :

浅表监视对象的属性,并在任何以下情况触发属性发生变化(对于数组,这意味着监视数组项目;对于对象图,这意味着要监视属性).如果一个检测到更改后,将触发侦听器回调.

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties). If a change is detected, the listener callback is fired.

因此,对于 Array ,它将对 Array 的项目执行监视,在您的情况下,这意味着监视功能如果您在 Array 中添加或删除项目,则将被触发.如果您有对象的 Array ,则Angular不会对这些对象执行深层的 $ watch .

So for an Array it will perform a shallow watch on the items of the Array, which in your case means that the watch function will get triggered if you add or remove items from the Array. If you have an Array of objects, Angular won't perform a deep $watch on those objects.

正如@GregL在下面的评论中指出的那样: $ scope.$ watchCollection 的重点是能够执行 shallow $ watch Object Array 上,因为深层的 $ watch 昂贵得多,尽管有时需要这样做.

As @GregL has pointed out in the comment bellow: the point of $scope.$watchCollection is to be able to do a shallow $watch on an Object or an Array, since a deep $watch is much more expensive, although sometimes it's needed.

我要添加到@GregL注释中的唯一一件事是,我们常常忘记了 $ watch 函数(第一个参数)的 watchExpression 可用于跟踪大型 Object Array 的非常具体部分的变化的函数,在许多情况下,我们可以编写该函数而不是使用深层次的函数 $ watch ,这将使 $ watch 更加高效.

The only thing that I would add to @GregL's comment is that very often we forget that the watchExpression of the $watch function (the first parameter) can also be function that can be used for tracking the changes of a very concrete part of a large Object or Array, there are many cases when we could write that function instead of using a deep $watch, which would make the $watch much more efficient.

这篇关于为什么$ scope.$ watch有效,而$ scope.$ watchCollection不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆