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

混江龙づ霸主 提交于 2019-11-27 09:05:24

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.

There are multiple reasons to avoid track by $index

  • Avoid using track by $index when using one-time bindings
  • Avoid track by $index when there is a unique property identifier
  • Other Examples of problems with track by $index

Avoid using track by $index when using one-time bindings

The documentation specifically states that track by $index should be avoided when using one-time bindings.

From the Docs:

Avoid using track by $index when the repeated template contains one-time bindings. In such cases, the nth DOM element will always be matched with the nth item of the array, so the bindings on that element will not be updated even when the corresponding item changes, essentially causing the view to get out-of-sync with the underlying data.

— AngularJS ng-repeat Reference - Tracking and Duplicates


Avoid track by $index when there is a unique property identifier

Avoid track by $index when there is a unique property identifier to work with. When working with objects that are all unique, it is better to let ng-repeat to use its own tracking instead of overriding with track by $index.

From the Docs:

If you are working with objects that have a unique identifier property, you should track by this identifier instead of the object instance. Should you reload your data later, ngRepeat will not have to rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones. For large collections, this significantly improves rendering performance.

— AngularJS ng-repeat Directive API Reference - Tracking


Other Examples of problems with track by $index

I have also seen problems when objects are added and removed from arrays of objects.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!