Optimizing the application using track by in ng-repeat
By default, ng-repeat
creates a DOM node for each item in the collection and destroys that DOM node when the item is removed. It is often the case that this is suboptimal for your application's performance, as a constant stream of re-rendering a sizeable collection will rarely be necessary at the repeater level and will tax your application's performance heavily. The solution is to utilize the track by
expression, which allows you to define how AngularJS associates DOM nodes with the elements of the collection.
How to do it…
When track by $index
is used as an addendum to the repeat expression, AngularJS will reuse any existing DOM nodes instead of re-rendering them.
The original, suboptimal version is as follows:
<div ng-repeat="element in largeCollection"> <!-- element repeater content --> </div>
The optimized version is as follows:
<div ng-repeat="element in largeCollection track by $index">
<!-- element repeater...