最近剛好需要用到 ng-repeat 的遍歷輸出,順手整理成一篇筆記。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ng-repeat directive</title>
</head>
<body ng-app="myApp">
<table ng-controller="CartController">
<caption>我的購物車</caption>
<tr>
<th>序號</th>
<th>商品</th>
<th>單價</th>
<th>數量</th>
<th>金額</th>
<th>操作</th>
</tr>
<tr ng-repeat="item in items">
<td>{{$index + 1}}</td>
<td>{{item.name}}</td>
<td>{{item.price | currency}}</td>
<td><input ng-model="item.quantity"></td>
<td>{{item.quantity * item.price | currency}}</td>
<td>
<button ng-click="remove($index)">Remove</button>
</td>
</tr>
</table>
<script src="js/angular-1.3.0.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('CartController', function ($scope) {
$scope.items = [
{ name: "蘋果 iPhone7", quantity: 1, price: 5088.00 },
{ name: "榮耀Magic", quantity: 1, price: 3699.00 },
{ name: "vivo X9", quantity: 2, price: 2798.00 }
];
// $index 包含了 ng-repeat 過程中的循環計數
$scope.remove = function (index) {
$scope.items.splice(index, 1);
};
});
</script>
</body>
</html>
ng-repeat 指令掛在需要重複輸出的元素上。表達式中的 items 對應控制器上的陣列變數,item 則是替「陣列中的單一元素」取的別名,命名完全自訂。
$index 回傳目前的索引序號,從 0 開始計算,因此畫面上要顯示第幾筆時得寫成 $index + 1。除了它,Angular 還內建了幾個方便的位置判斷變數:
・$first:目前元素是否為集合中的第一個
・$middle:是否為中間元素
・$last:是否為最後一個
・$even、$odd:索引的奇偶性
這些都回傳布林值,很適合拿來控制首尾樣式或分隔線。
ng-repeat 每個迭代都會建立自己的子 scope,所以 item、$index 這些變數不會污染父控制器。另外,範例中quantity 直接用 ng-model 雙向綁定,小計欄位便會即時重算;删除時傳入 $index 交給 splice 處理即可,這也是 $index 最實用的場合之一。