Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does AngularJS $watch these cases in an ng-repeat?

Tags:

angularjs

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>
like image 447
Bradford Avatar asked Mar 26 '13 20:03

Bradford


1 Answers

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.

like image 192
Mark Rajcok Avatar answered Nov 14 '22 00:11

Mark Rajcok