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.现象
- <ul ng-app="myApp" ng-controller="myCtrl">
- <li ng-repeat="x in items">
- <strong>{{x}}</strong>
- </li>
- </ul>
- <script>
- //使用ng-repeat 重复 html代码
- var app = angular.module('myApp', []);
- app.controller('myCtrl', function ($scope) {
- $scope.items = [1, 2, 3, 2];
- });
- </script>
当数组中有重复项时,抛出异常
点击异常链接,没有看到异常
2.解决方法
默认在ng-repeat的时候每一个item都要保证是唯一的,否则console就会打出error告诉你哪个key/value是重复的。
指定跟踪值唯一可以了
- <ul ng-app="myApp" ng-controller="myCtrl">
- <li ng-repeat="x in items track by $index">
- <strong>{{x}}</strong>
- </li>
- </ul>
- <script>
- //使用ng-repeat 重复 html代码
- var app = angular.module('myApp', []);
- app.controller('myCtrl', function ($scope) {
- $scope.items = [1, 2, 3, 2];
- });
- </script>