轉載出處:http://www.cnblogs.com/liulangmao/p/3716457.html
視圖的迭代和它的ng-repeat屬性綁定的數據是實時綁定的,一旦數據發生了改變,視圖也會立即更新迭代.
還是剛纔的那個例子,給它添加一個添加數據按鈕和一個刪除數據按鈕.
<!DOCTYPE html> <html ng-app> <head> <title>4.1.迭代</title> <meta charset="utf-8"> <script src="../angular.js"></script> <script src="script.js"></script> </head> <body> <div ng-controller="StudentList"> <ul> <li ng-repeat="student in students"> <span class="index">{{$index+1}}</span><span class="name"><a href="/student/view/{{student.id}}" class="name">{{student.name}}</a></span><span class="score">{{student.score}}</span> </li> </ul> <button ng-click="insertDog()">添加</button> <button ng-click="delLast()">刪除</button> </div> </body> </html>
function StudentList ($scope){ $scope.students = [{"name":"code_bunny","score":"100","id":"001"},{"name":"white_bunny","score":"90","id":"002"},{"name":"black_bunny","score":"80","id":"003"}]; $scope.insertDog = function(){ $scope.students.splice($scope.students.length,0,{"name":"code_dog","score":"101","id":"004"}) }; $scope.delLast = function(){ $scope.students.splice(-1,1) } }
insertDog方法和selLast方法,分別是往students數組裏添加項和刪除項.
可以看到,一旦students數組發生變化,通過ng-repeat屬性綁定它的li項的迭代也會實時更新:
一開始:
點擊添加後:
點擊兩次刪除後: