1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>ng-repeat directive</title> 6 </head> 7 <body ng-app="myApp"> 8 <table ng-controller="CartController"> 9 <caption>我的购物车</caption> 10 <tr> 11 <th>序号</th> 12 <th>商品</th> 13 <th>单价</th> 14 <th>数量</th> 15 <th>金额</th> 16 <th>操作</th> 17 </tr> 18 <tr ng-repeat="item in items"> 19 <td>{{$index + 1}}</td> 20 <td>{{item.name}}</td> 21 <td>{{item.price | currency}}</td> 22 <td><input ng-model="item.quantity"></td> 23 <td>{{item.quantity * item.price | currency}}</td> 24 <td> 25 <button ng-click="remove($index)">Remove</button> 26 </td> 27 </tr> 28 </table> 29 30 <script src="js/angular-1.3.0.14/angular.min.js"></script> 31 <script> 32 var app = angular.module('myApp', []); 33 app.controller('CartController',function($scope){ 34 $scope.items = [ 35 {name: "苹果 iPhone7", quantity: 1, price: 5088.00}, 36 {name: "荣耀Magic", quantity: 1, price: 3699.00}, 37 {name: "vivo X9", quantity: 2, price: 2798.00} 38 ]; 39 //$index包含了ng-repeat过程中的循环计数 40 $scope.remove = function (index) { 41 $scope.items.splice(index, 1); 42 } 43 }) 44 </script> 45 </body> 46 </html>
ng-repeat指令生命在需要循环内容的元素上,items和控制器上的变量名对应,item是为数组中单个对象起的别名。
$index可以返回当前引用对象的序号,从0开始,另外还有$first、$middle、$last可以返回布尔值,用于告诉你
当前元素是否是集合中的第一个中间的最后一个元素。