ng-repeat 是 angular 中可以用來透過迴圈方式來取得陣列中各個 item 值的方法
基本範例
main.js
var ballApp = angular.module('ballApp', []);
ballApp.controller('testCtrl', ['$scope', function($scope) {
// 姓名陣列
$scope.names = ['Johnson', 'Tom', 'Jim'];
}]);
<body ng-controller="testCtrl">
<ul>
<!-- 透過 i in array 的方式來描述迴圈走訪 -->
<!-- $index 為 ng-repeat 中提供的索引值變數 -->
<li ng-repeat="name in names">{{$index}} {{name}}</li>
</ul>
</body>
注意
ng-repeat 並不是一般迴圈用法而已,以下這個例子會產生錯誤:
// 當陣列中有值是相同的情況下,使用基本範例這樣的 ng-repeat 會產生錯誤 $scope.names = ['Johnson', 'Johnson', 'Johnson'];
解決方法是在 ng-repeat 中描述要依照 item 走訪
<body ng-controller="testCtrl">
<ul>
<!-- 依照 item 走訪 -->
<li ng-repeat="name in names track by $index">{{$index}} {{name}}</li>
</ul>
</body>