$watchGroup 与 $watchCollection? [英] $watchGroup vs $watchCollection?
问题描述
有两种观察一组变量的方法在角.但它们之间有什么区别?
There're 2 ways to watch a group of variables in Angular. But what's the difference between them?
他们似乎都做浅表.是否存在一种明显优于另一种的情况?
They both seem to do shallow watches. Are there situations where one is obviously preferable over the other?
推荐答案
$watchCollection
将浅层监视单个对象的属性,并在其中一个对象发生变化时通知您.
$watchCollection
will shallow watch the properties on a single object and notify you if one of them changes.
$watchGroup
但是监视一组单独的监视表达式.
$watchGroup
however watches a group of individual watch expressions.
它们在功能上并不等效.$watchGroup
可以用于当你想观察大量的表达式,这些表达式都应该响应同一个回调——这些可以是针对不同对象的单独表达式.这可用于观看 'foo'
、'foo.bar'
和 'baz.qux'
.这是 3 个不同的目标 - foo
、foo
的 bar
属性和 baz
的 qux
属性,但它们都将委托给同一个处理程序.
They are not functionally equivalent. $watchGroup
could be used when you want to watch a multitude of expressions that should all respond to the same callback - these could be individual expressions that target different objects. This could be used for watching 'foo'
, 'foo.bar'
, and 'baz.qux'
. These are 3 different targets - foo
, foo
's bar
property and baz
's qux
property, but they will all delegate to the same handler.
相比之下,$watchCollection
只会浅层观察单个对象.这对于可能会大量更改其属性的对象(例如 - 我们自己的 $scope
)来说更好.与我们的垃圾名称示例保持一致,要实现与上述相同的效果,您只需要查看 foo
和 baz
,但是您会收到 中的任何更改的通知foo
和 baz
(而不是仅仅在 foo
本身、foo.bar
和 baz.qux
.
By contrast, $watchCollection
will only shallow watch a single object. This makes it better for an object that might change it's properties a lot (for example - our very own $scope
). In keeping with our rubbish name examples, to achieve the same as above you would only want to watch foo
and baz
, but you would be notified of any changes in foo
and baz
(as opposed to just being notified for the changes on foo
itself, foo.bar
and baz.qux
.
这篇关于$watchGroup 与 $watchCollection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!