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可以返回布爾值,用於告訴你
當前元素是否是集合中的第一個中間的最后一個元素。