Angularjs ng-repeat 数组 - 重复值

Angularjs ng-repeat array - duplicate values

所以我刚开始使用 angular JS,在处理数组时对 ng-repeat 有点困惑。下面的代码不能正常工作...但是当我将 dayNames 更改为一个对象并给它键值对时就没问题了。

var myApp = angular.module('exampleApp', []);

myApp.controller("dayCtrl",function($scope){
 $scope.dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="exampleApp">
<head>
 <script src="angular.js"></script>
 <script src="controller.js"></script> 
</head>
<body ng-controller="dayCtrl">
 <h2>Hello, these are the days of the week</h2>
 <ul>
  <li ng-repeat="day in dayNames">{{day}}</li>
 </ul>
</body>
 

</html>

它不能按原样工作,因为数组中有重复项。当您重复基元数组时,angular 用于将数组中的项目与 DOM 元素相关联的默认唯一键是数组本身中的项目。当然,在您的情况下,它不是唯一的,它会导致中继器重复错误。

您也可以通过使用 track by $index 来避免这种情况,这使得索引成为标识符。

ng-repeat="day in dayNames track by $index"

当您使用对象数组(没有跟踪依据)时,angular 将唯一 ID 添加到数组的每个项目上名为 $$hashkey 的新 属性。然后,此 属性 被用作关联 DOM 元素与数组中相应项的键。在数组中移动相同的对象将以相同的方式在 DOM 中移动 DOM 元素。因此,当您使用对象数组时,您看不到任何问题,因为所有这些哈希键都是唯一的。

var myApp = angular.module('exampleApp', []);

myApp.controller("dayCtrl",function($scope){
 $scope.dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="exampleApp">
<head>
 <script src="angular.js"></script>
 <script src="controller.js"></script> 
</head>
<body ng-controller="dayCtrl">
 <h2>Hello, these are the days of the week</h2>
 <ul>
  <li ng-repeat="day in dayNames track by $index">{{day}}</li>
 </ul>
</body>
 

</html>