When not to use 'track by $index' in an AngularJS ng-repeat?

前端 未结 2 457
北荒
北荒 2020-11-29 10:38

I recently got the console error `

Error: [ngRepeat:dupes] duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys..

2条回答
  •  甜味超标
    2020-11-29 10:53

    It has a disadvantage,

    'track by' expression tracks by index in the array. It means that as long as the index stays the same, angularjs thinks it's the same object.

    So if you replace any object in the array, angularjs think it didn't change because the index in the array is still the same. Because of that the change detection wont trigger when you expect it would.

    Take a look at this example

    Try to change the name, nothing happens. Remove track by index, it works. add track by item.name, it still works.

提交回复
热议问题