当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > AngularJS基础 ng-repeat 指令简单示例

AngularJS基础 ng-repeat 指令简单示例

2018年05月29日  | 移动技术网IT编程  | 我要评论

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 指令的基础资料整理,后续继续补充。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网