檢視的迭代和它的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項的迭代也會實時更新:
一開始:
點選新增後:
點選兩次刪除後: