AngularJs ng-repeat重复项异常解决方案
ng-repeat="v in arr track by $index"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body ng-app="myApp">
<!--
ng-init:初始化数据
ng-init="person={name:'小明'}"
-->
<div ng-app="myApp" ng-controller="myController">
<input type="text" ng-model="iptValue">
<input type="button" ng-click="clickFn()" value="按钮">
<ul>
<li ng-repeat="v in arr track by $index">{{v}}</li>
</ul>
</div>
</body>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript">
// [] ---> 依赖
var app = angular.module("myApp",[]);
// $scope作用域:作用域范围myController
app.controller("myController",function($scope){
$scope.arr = ["111","222"];
$scope.clickFn = function(){
var v = $scope.iptValue;
$scope.arr.push(v);
$scope.iptValue = "";
}
});
</script>
</html>
1.现象
当数组中有重复项时,抛出异常点击异常链接,没有看到异常
2.解决方法
默认在ng-repeat的时候每一个item都要保证是唯一的,否则console就会打出error告诉你哪个key/value是重复的。
指定跟踪值唯一可以了