ng-repeat="v in arr track by $index"

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>Document</title>
  6. </head>
  7. <body ng-app="myApp">
  8. <!--
  9. ng-init:初始化数据
  10. ng-init="person={name:'小明'}"
  11. -->
  12. <div ng-app="myApp" ng-controller="myController">
  13. <input type="text" ng-model="iptValue">
  14. <input type="button" ng-click="clickFn()" value="按钮">
  15. <ul>
  16. <li ng-repeat="v in arr track by $index">{{v}}</li>
  17. </ul>
  18. </div>
  19. </body>
  20. <script type="text/javascript" src="angular.min.js"></script>
  21. <script type="text/javascript">
  22. // [] ---> 依赖
  23. var app = angular.module("myApp",[]);
  24. // $scope作用域:作用域范围myController
  25. app.controller("myController",function($scope){
  26. $scope.arr = ["111","222"];
  27. $scope.clickFn = function(){
  28. var v = $scope.iptValue;
  29. $scope.arr.push(v);
  30. $scope.iptValue = "";
  31. }
  32. });
  33. </script>
  34. </html>
AngularJs ng-repeat重复项异常解决方案-LMLPHP
 

1.现象

  1. <ul ng-app="myApp" ng-controller="myCtrl">
  2. <li ng-repeat="x in items">
  3. <strong>{{x}}</strong>
  4. </li>
  5. </ul>
  6. <script>
  7. //使用ng-repeat 重复 html代码
  8. var app = angular.module('myApp', []);
  9. app.controller('myCtrl', function ($scope) {
  10. $scope.items = [1, 2, 3, 2];
  11. });
  12. </script>

当数组中有重复项时,抛出异常

AngularJs ng-repeat重复项异常解决方案-LMLPHP

点击异常链接,没有看到异常

2.解决方法

默认在ng-repeat的时候每一个item都要保证是唯一的,否则console就会打出error告诉你哪个key/value是重复的。

指定跟踪值唯一可以了

  1. <ul ng-app="myApp" ng-controller="myCtrl">
  2. <li ng-repeat="x in items track by $index">
  3. <strong>{{x}}</strong>
  4. </li>
  5. </ul>
  6. <script>
  7. //使用ng-repeat 重复 html代码
  8. var app = angular.module('myApp', []);
  9. app.controller('myCtrl', function ($scope) {
  10. $scope.items = [1, 2, 3, 2];
  11. });
  12. </script>

AngularJs ng-repeat重复项异常解决方案-LMLPHP

05-28 04:01