8

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>
Bradford
  • 4,143
  • 2
  • 34
  • 44

1 Answers1

7

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.

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • 5
    That's crazy about `x | filter`. I don't understand why that is. Maybe they assume filter is not going to be a pure function? – Bradford Mar 26 '13 at 20:31
  • 2
    I was quite surprised by that also. – Mark Rajcok Mar 26 '13 at 20:34
  • 1
    Updated link for the ng-repeat source code: https://github.com/angular/angular.js/blob/v1.6.x/src/ng/directive/ngRepeat.js. Looks like they now use $watchCollection to do shallow checks. Thank you Mark! – John Lee Oct 22 '18 at 04:31