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

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>
1090294-20170411100657094-1464294228.gif
 

1.现象

[html]   view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  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>  
当数组中有重复项时,抛出异常



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

2.解决方法

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

指定跟踪值唯一可以了

[html]   view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  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>  

转载于:https://www.cnblogs.com/ChenChunChang/p/6692247.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值