问题:ng-repeat 的循环对象是不能出现重复项的,所以如果有重复的就会报错,应该是 key value的问题吧,不是很了解内部运行机制;经过查询发现 在 循环后面加上 track by $index 就会解决问题,也就可以有重复对象了
报错:
划重点
解决办法:加上 track by $index
<ul> <li ng-repeat="x in names track by $index"> {{x}}.{{lastname}} <button ng-click="delPerson($index)">删除</button> </li> </ul>
完整栗子:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script> </head> <body> <div ng-controller="myContrl"> <h1>{{lastname}}家族成员:</h1> <ul> <li ng-repeat="x in names track by $index"> {{x}}.{{lastname}} <button ng-click="delPerson($index)">删除</button> </li> </ul> <p>添加成员: <input type="text" ng-model="name" placeholder="请输入需要添加的成员名字"> </p> <button ng-click="addPerson(name)">确认添加</button> </div> <script> angular.module('myapp', []) .controller('myContrl', function ($scope, $rootScope) { // $rootScope 根作用域,在素有的控制器中都可以用 $scope.name = ''; $scope.names = ["name1", "name2", "name3", "name4", "name4"]; $scope.sayHellow = function () { $scope.greeting = "Hello," + $scope.name + "!"; } $scope.delPerson = function (index) { // 将点击删除的对象从数组中移除,angular会自动更新列表 $scope.names.splice(index, 1); } $scope.addPerson = function (name) { // 输入的对象添加到数组,angular会自动更新列表 $scope.names.push(name); } $rootScope.lastname = "Refsnes"; }); //手动初始化 angular.bootstrap(document, ['myapp']); </script> </body> </html>