問題:ng-repeat 的循環對象是不能出現重複項的,因此若是有重複的就會報錯,應該是 key value的問題吧,不是很瞭解內部運行機制;通過查詢發現 在 循環後面加上 track by $index 就會解決問題,也就能夠有重複對象了html
報錯:bootstrap
劃重點數組
解決辦法:加上 track by $indexapp
<ul> <li ng-repeat="x in names track by $index"> {{x}}.{{lastname}} <button ng-click="delPerson($index)">刪除</button> </li> </ul>
完整栗子:spa
<!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>