Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  182] [ 1]  / answers: 1 / hits: 166643  / 10 Years ago, mon, march 31, 2014, 12:00:00

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>

More From » angularjs

 Answers
12

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>

[#71698] Friday, March 28, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gerardamosy

Total Points: 600
Total Questions: 116
Total Answers: 102

Location: Ukraine
Member since Tue, May 30, 2023
1 Year ago
;