DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> AngularJS基礎 ng-repeat 指令簡單示例
AngularJS基礎 ng-repeat 指令簡單示例
編輯:關於JavaScript     

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 指令的基礎資料整理,後續繼續補充。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved