angularJS ng-repeat指令中使用track by子语句解决重复数据遍历的错误

我们可以使用ng-repeat指令遍历一个javascript数组,当数组中有重复元素的时候,angularjs会报错:

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。下面的代码就会报错:

<script src="https://cdn.bootcss.com/angular.js/1.6.6/angular.min.js"></script>
<div ng-controller="myContrl">    
  <h1>{{lastname}}家族成员:</h1>    
    <li ng-repeat="x in names">
      {{x}}.{{lastname}} 
      <button ng-click="delPerson($index)">删除</button> 
  <p>添加成员:
    <input type="text" ng-model="name" placeholder="请输入需要添加的成员名字"></p>
  <button ng-click="addPerson(name)">确认添加</button>
</div>


angular.module('myapp',[])        
  .controller('myContrl',function($scope,$rootScope){            
  // $rootScope 根作用域,在素有的控制器中都可以用            
  $scope.name = '';            
  $scope.names = ["name1","name2","name3","name4","name4"];            
  $scope.sayHellow = function(){                
    $scope.greeting = "Hello," + $scope.name + "!";               
  $scope.delPerson = function(index){
    // 将点击删除的对象从数组中移除,angular会自动更新列表
    $scope.names.splice(index,1);            
  $scope.addPerson = function(name){                
    // 输入的对象添加到数组,angular会自动更新列表               
    $scope.names.push(name);            
  $rootScope.lastname = "Refsnes";