Understanding the ngRepeat 'track by' expression

I'm having difficulty understanding how tracking ng-repeat expression works in angularjs. The documentation is very scarce: http://docs.angularjs.org/api/ng/directive/ngRepeat

Can you explain the difference between these two pieces of code in terms of data binding and other relevant aspects?

c: track by $index

 <!--names is an array--> <div ng-repeat="(key, value) in names track by $index"> <input ng-model="value[key]"> </div> 

without (same conclusion)

 <!--names is an array--> <div ng-repeat="(key, value) in names"> <input ng-model="value[key]"> </div> 
+73
javascript angularjs angularjs-ng-repeat
Mar 31 '14 at 12:16
source share
3 answers

You can track by $index if your data source has duplicate identifiers

for example: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]

You cannot iterate over this collection when using the id id as an id (duplicate id: 1).

DOES NOT WORK:

 <element ng-repeat="item.id as item.name for item in dataSource"> // something with item ... </element> 

but you can using track by $index :

 <element ng-repeat="item in dataSource track by $index"> // something with item ... </element> 
+64
Mar 31 '14 at 12:28
source share

short summary:

track by used to link your data to DOM generation (and mainly re-generation) done with ng-repeat.

when you add track by , you basically tell angular to create one DOM element for each data object in this collection

this can be useful when paging and filtering, or in any case, when objects are added or removed from the ng-repeat list.

usually without track by angular, it will associate the DOM objects with the collection by introducing the expando property - $$hashKey - into your JavaScript objects and will regenerate it (and re-associate the DOM object) with each change.

full explanation:

http://www.bennadel.com/blog/2556-using-track-by-with-ngrepeat-in-angularjs-1-2.htm

more practical guide:

http://www.codelord.net/2014/04/15/improving-ng-repeat-performance-with-track-by/

(track available in angular> 1.2)

+48
04 Oct '14 at
source share

If you work with objects, you track by identifier (for example, $ index) instead of the entire object, and later you load your data, ngRepeat will not rebuild the DOM elements for elements that are already present , even if the JavaScript objects in the collection are replaced with new ones.

+6
Sep 08 '16 at 18:53 on
source share



All Articles