angular学习笔记(七)-迭代2

视图的迭代和它的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项的迭代也会实时更新:


一开始:
angular学习笔记(七)-迭代2

点击添加后:
angular学习笔记(七)-迭代2

点击两次删除后:
angular学习笔记(七)-迭代2

 

你可能感兴趣的:(Angular)