Sponsored Links

November 14, 2017

How to fix Duplicate error with ng-repeat in angularjs

While working with angularjs directive ng-repeat, you may have encountered with the problem of duplicate error with ng-repeat. Here is the proper description and problem and the solution of it.
In order for angular to know exactly what items have changed, it calculates a hash for each item within the ng-repeat. Otherwise, if you had 5 items with the exact same contents, how would it be able to determine which of those items was modified? When it determines that duplicates exist, it prints out that error.
In this case, to get around this, there's a track by expression that you can add to the end of the ng-repeat expression. This expression lets you define a property that uniquely identifies each item in the array. For arrays with primitive types, one approach is to use track by $index which tracks each item in the array by the objects position within the array.
  
<div ng-repeat="num in [1, 2, 2, 3] track by $index">
 {{num}}
</div>
  
 
By adding the track by $index, you will not get the duplicate error. 

No comments:

Post a Comment