AngularJS基础 ng-repeat 指令简单示例
程序员文章站
2022-05-05 16:43:11
angularjs ng-repeat 指令
angularjs 实例
循环输出多个标题:
angularjs ng-repeat 指令
angularjs 实例
循环输出多个标题:
<!doctype html> <html> <head> <meta charset="utf-8"> <script src="http://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>
定义和用法
ng-repeat 指令用于循环输出指定次数的 html 元素。
集合必须是数组或对象。
语法
<element ng-repeat="expression"></element>
所有的 html 元素都支持该指令。
参数值
值 | 描述 |
---|---|
expression | 表达式定义了如何循环集合。 表达式实例规则: x in records (key, value) in myobj x in records track by $id(x) |
更多实例
angularjs 实例
使用数组循环输出一个表格:
<!doctype html> <html> <head> <meta charset="utf-8"> <script src="http://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 |
angularjs 实例
使用对象循环输出一个表格:
<!doctype html> <html> <head> <meta charset="utf-8"> <script src="http://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 |
以上就是对angularjs ng-repeat 指令的基础资料整理,后续继续补充。