Understanding the ngRepeat 'track by' expr

2020-01-27 00:22发布

I'm having difficulties understanding how the track by expression of ng-repeat in angularjs works. The documentation is very scarce: http://docs.angularjs.org/api/ng/directive/ngRepeat

Can you explain what the difference between those two snippets of code is in terms of databinding and other relevant aspects?

with: 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 output)

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

3条回答
Fickle 薄情
2楼-- · 2020-01-27 00:44

If you are working with objects track by the identifier(e.g. $index) instead of the whole object and you reload your data later, ngRepeat will not rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones.

查看更多
家丑人穷心不美
3楼-- · 2020-01-27 00:53

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

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

You can't iterate this collection while using 'id' as identifier (duplicate id:1).

WON'T WORK:

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

but you can, if using track by $index:

<element ng-repeat="item in dataSource track by $index">
  // something with item ...
</element>
查看更多
太酷不给撩
4楼-- · 2020-01-27 01:01

a short summary:

track by is used in order to link your data with the DOM generation (and mainly re-generation) made by ng-repeat.

when you add track by you basically tell angular to generate a single DOM element per data object in the given collection

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

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

full explanation:

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

a more practical guide:

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

(track by is available in angular > 1.2 )

查看更多
登录 后发表回答