AngularJS ng-repeat 指令
定義和用法
ng-repeat
指令將一組HTML重復指定的次數。
HTML 集合中的每個項目將重復一次。
集合必須是數組或對象。
注意:重復的每個實例都會獲得自己的作用域,該作用域由當前項目組成。
如果您有一個對象集合,ng-repeat
指令非常適合制作HTML表格,為每個對象顯示一個表格行,并為每個對象屬性顯示一個表格數據。請參閱下面的示例。
實例
例子 1
為 records 數組中的每個項目寫一個標題:
<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 = [ "Alfreds Futterkiste", "Berglunds snabbköp", "Centro comercial Moctezuma", "Ernst Handel", ] }); </script> </body>
例子 2
為 records 數組中的每個項目寫一個表格行:
<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öp", "Country" : "Sweden" },{ "Name" : "Centro comercial Moctezuma", "Country" : "Mexico" },{ "Name" : "Ernst Handel", "Country" : "Austria" } ] }); </script>
例子 3
為對象中的每個屬性寫一個表格行:
<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>
語法
<element ng-repeat="expression"></element>
所有 HTML 元素都支持。
參數
參數 | 描述 |
---|---|
expression |
指定如何循環集合的表達式。 合法表達式示例:
|