ng-repeat 用來依集合內容重複輸出 HTML 元素。它是 AngularJS 裡使用頻率最高的指令之一,幾乎任何列表、表格、卡片牆都靠它。待迭代的集合必須是陣列或物件。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h1 ng-repeat="x in records">{{x}}</h1>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = ["菜鳥教程1", "菜鳥教程2", "菜鳥教程3", "菜鳥教程4"];
});
</script>
</body>
</html>
<element ng-repeat="expression"></element>
所有 HTML 元素都支援。
• x in records——遍歷陣列,x 為元素值。
• (key, value) in myObj——遍歷物件,同時拿到鍵與值。
• x in records track by $id(x)——用 track by 指定追蹤身分,可避免重複渲染造成的效能問題。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp">
<table ng-controller="myCtrl" border="1">
<tr ng-repeat="x in records">
<td>{{x.Name}}</td>
<td>{{x.Country}}</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [
{ "Name": "Alfreds Futterkiste", "Country": "Germany" },
{ "Name": "Berglunds snabbk", "Country": "Sweden" },
{ "Name": "Centro comercial Moctezuma", "Country": "Mexico" },
{ "Name": "Ernst Handel", "Country": "Austria" }
];
});
</script>
</body>
</html>
輸出結果:
Alfreds Futterkiste / Germany
Berglunds snabbk / Sweden
Centro comercial Moctezuma / Mexico
Ernst Handel / Austria
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp">
<table ng-controller="myCtrl" border="1">
<tr ng-repeat="(x, y) in myObj">
<td>{{x}}</td>
<td>{{y}}</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.myObj = {
"Name": "Alfreds Futterkiste",
"Country": "Germany",
"City": "Berlin"
};
});
</script>
</body>
</html>
輸出結果:Name / Alfreds Futterkiste、Country / Germany、City / Berlin。這裡 x 是鍵名、y 是對應的值。
用 track by 提升效能。當資料是從伺服器重新撈回來、內容幾乎沒變時,沒有 track by 的話 Angular 會比對整个物件的參照,一旦不同就把整批 DOM 砍掉重建。加上 track by x.id 後只會更新真正變動的節點。
ng-repeat 會自建子 scope。因此在裡面寫 ng-model 時,若想改到外層的某個屬性,記得用 ng-model="$parent.selectedId",否則會不小心建立一個只存在於子 scope 的新變數。
可用的特殊變數:$index(索引)、$first、$last、$middle、$even、$odd,做序號或奇偶樣式時很好用。
篩選與排序可以直接串在運算式後面:ng-repeat="x in records | filter:{Country:'Sweden'} | orderBy:'Name'"。