AngularJS 如何在 ng-repeat 中 $watch 这些案例? [英] How does AngularJS $watch these cases in an ng-repeat?

查看:22
本文介绍了AngularJS 如何在 ng-repeat 中 $watch 这些案例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 AngularJS 在 ng-repeat 上设置了一些监视.此时设置的是什么类型的手表?

另外,有人能解释一下在每种情况下会发生什么吗?我想知道如果我有很多项目,那么用户就不会被我用其他方式编写的手表所困扰.

一个

<div>{{item.property}}</div>

两个

<div>{{item.property |myFormatter}}

三个

<div>{{format(item.property)}}</div>

四个

<div>{{item.something()}}</div>

解决方案

每个 ng-repeat 都会在 items 上设置一个 $watch.(如果您查看 ng-repeat源码,大部分是$watch方法的watchExpression函数).每次 Angular digest cycle 运行时,item 中的每个 itemcode>items 将被这个 watch 函数检查.(请注意,在一个摘要循环中,此监视函数可能会被多次调用).

每个 {{}} 设置一个 $watch.如果诸如 item.property 之类的内容在 {{}} 中,则每个摘要周期至少对其进行一次脏检查.

如果函数在 {{}} 中,那么每个摘要周期至少调用一次该函数.

我不确定 x |过滤器,但this fiddle 似乎表明过滤器在每个摘要中至少被调用一次循环,即使 x 没有改变.

I understand that AngularJS sets up some watches on ng-repeat. What type of watch is setup at this point?

Also, can someone explain what happens in each of these scenarios? I want to know in the event that I have many items, so the user isn't being bogged down by watches that could have been eliminated had I written it some other way.

One

<div ng-repeat="item in items">
  <div>{{item.property}}</div>
</div>

Two

<div ng-repeat="item in items">
  <div>{{item.property | myFormatter}}</div>
</div>

Three

<div ng-repeat="item in items">
  <div>{{format(item.property)}}</div>
</div>

Four

<div ng-repeat="item in items">
  <div>{{item.something()}}</div>
</div>

解决方案

Each ng-repeat will set up a $watch on items. (If you look at the ng-repeat source code, most of it is the watchExpression function of the $watch method). Each time an Angular digest cycle runs, each item in items will be examined by this watch function. (Note that in a digest cycle, this watch function could be called more than once).

Each {{}} sets up a $watch. If something like item.property is inside the {{}}s, it is dirty checked at least once per digest cycle.

If a function is inside {{}}s, then that function is called at least once per digest cycle.

I'm not sure about x | filter, but this fiddle seems to indicated that the filter is called at least once every digest cycle, even if x doesn't change.

这篇关于AngularJS 如何在 ng-repeat 中 $watch 这些案例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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