AngularJS ng-repeat 指令

实例

为记录数组中的每个项写入一个标题:

  1. <!DOCTYPE html>
  2. <html>
  3. <script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
  4. <body ng-app="myApp" ng-controller="myCtrl">
  5. <h1 ng-repeat="x in records">{{x}}</h1>
  6. <script>
  7. var app = angular.module("myApp", []);
  8. app.controller("myCtrl", function($scope) {
  9. $scope.records = [
  10. "Alfreds Futterkiste",
  11. "Berglunds snabbkp",
  12. "Centro comercial Moctezuma",
  13. "Ernst Handel",
  14. ]
  15. });
  16. </script>
  17. </body>
  18. </html>

定义与用法

ng-repeat 指令根据给定的次数来重复 HTML。

集合中的每个项目都会重复一次 HTML。

集合必须是数组或对象。

注意:重复的每个实例都有自己的作用域,包括当前项。

如果您有一个对象集合,ng-repeat 指令非常适合创建一个HTML表,为每个对象显示一个表行,为每个对象属性显示一个表数据。见下面的例子。


语法

  1. <element ng-repeat="expression"></element>

由所有 HTML 元素支持。


参数值

描述
expression指定如何循环集合的表达式

有效表达式实例:

x in records

(key, value) in myObj

x in records track by $id(x)

更多实例

实例

为记录数组中的每个项写一行表:

  1. <!DOCTYPE html>
  2. <html>
  3. <script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
  4. <body ng-app="myApp">
  5. <table ng-controller="myCtrl" border="1">
  6. <tr ng-repeat="x in records">
  7. <td>{{x.Name}}</td>
  8. <td>{{x.Country}}</td>
  9. </tr>
  10. </table>
  11. <script>
  12. var app = angular.module("myApp", []);
  13. app.controller("myCtrl", function($scope) {
  14. $scope.records = [
  15. {
  16. "Name" : "Alfreds Futterkiste",
  17. "Country" : "Germany"
  18. },
  19. {
  20. "Name" : "Berglunds snabbkp",
  21. "Country" : "Sweden"
  22. },
  23. {
  24. "Name" : "Centro comercial Moctezuma",
  25. "Country" : "Mexico"
  26. },
  27. {
  28. "Name" : "Ernst Handel",
  29. "Country" : "Austria"
  30. }
  31. ]
  32. });
  33. </script>
  34. </body>
  35. </html>
实例

为对象中的每个属性编写一个表行:

  1. <!DOCTYPE html>
  2. <html>
  3. <script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
  4. <body ng-app="myApp">
  5. <table ng-controller="myCtrl" border="1">
  6. <tr ng-repeat="(x, y) in myObj">
  7. <td>{{x}}</td>
  8. <td>{{y}}</td>
  9. </tr>
  10. </table>
  11. <script>
  12. var app = angular.module("myApp", []);
  13. app.controller("myCtrl", function($scope) {
  14. $scope.myObj = {
  15. "Name" : "Alfreds Futterkiste",
  16. "Country" : "Germany",
  17. "City" : "Berlin"
  18. }
  19. });
  20. </script>
  21. </body>
  22. </html>

分类导航