Javascript

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

本文主要是介绍AngularJS基础 ng-repeat 指令简单示例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

这篇关于AngularJS基础 ng-repeat 指令简单示例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!