The track by substatement is used in the AngularJS ng repeat instruction to solve the problem of repeated data traversal errors

  • 2021-07-13 03:55:29
  • OfStack

In this paper, the track by substatement in AngularJS ng-repeat instruction is used to solve the problem of repeated data traversal error. Share it for your reference, as follows:

We can use the ng-repeat instruction to traverse an JavaScript array. When there are duplicate elements in the array, AngularJS will report an error:

Error: [ngRepeat: dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: number: 1. The following code will report an error:


<html>
 <head>
  <script src="angular-1.2.2/angular.js"></script>
  <script>
     function rootController($scope,$rootScope,$injector)
     {
      $scope.dataList = [1,2,1];
     }
  </script>
 </head>
 <body ng-app ng-controller="rootController">
    <div ng-repeat="data in dataList">
      {{data}}
    </div>
 </body>
</html>

This is because ng-Repeat does not allow two objects of the same Id in collection.

For example: item in items is equivalent to item in items track by $id(item). This implies that the DOM elements will be associated by item identity in the array.

For basic data types such as numbers or strings, its id is its own value. Therefore, two identical numbers are not allowed in the array. To avoid this error, you need to define your own track by expression.

//Generate only 1 id in business
item in items track by item.id
//Or use the loop index variable $index directly
item in items track by $index

If it is javascript object type data, ng-repeat will not consider it the same object even if the content is 1 or 1. If you put dataList in the above code, you will not report an error. For example, $scope. dataList = [{"age": 10}, {"age": 10}];

For more readers interested in AngularJS related content, please check the topics of this site: "Introduction and Advanced Tutorial of AngularJS" and "Summary of AngularJS MVC Architecture"

I hope this article is helpful to everyone's AngularJS programming.


Related articles: