Chỉ thị ng-repeat
AngularJS
Ví dụ
Viết một tiêu đề cho mỗi mục trong mảng bản ghi:
<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 = [
"Alfreds Futterkiste",
"Berglunds snabbköp",
"Centro comercial Moctezuma",
"Ernst Handel",
]
});
</script>
</body>
Hãy tự mình thử »Định nghĩa và cách sử dụng
Lệnh ng-repeat
lặp lại một tập hợp HTML với số lần nhất định.
Bộ HTML sẽ được lặp lại một lần cho mỗi mục trong bộ sưu tập.
Bộ sưu tập phải là một mảng hoặc một đối tượng.
Lưu ý: Mỗi phiên bản lặp lại có phạm vi riêng, bao gồm mục hiện tại.
Nếu bạn có một bộ sưu tập các đối tượng, lệnh ng-repeat
là hoàn hảo để tạo một bảng HTML, hiển thị một hàng trong bảng cho mỗi đối tượng và một dữ liệu bảng cho mỗi thuộc tính đối tượng. Xem ví dụ dưới đây.
Cú pháp
< element ng-repeat=" expression "></ element >
Được hỗ trợ bởi tất cả các phần tử HTML.
Giá trị tham số
Value | Description |
---|---|
expression | An expression that specifies how to loop the collection. Legal Expression examples: x in records
(key, value) in myObj |
Thêm ví dụ
Ví dụ
Viết một hàng trong bảng cho mỗi mục trong mảng bản ghi:
<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öp",
"Country" : "Sweden"
},{
"Name" : "Centro comercial Moctezuma",
"Country" : "Mexico"
},{
"Name" : "Ernst Handel",
"Country" : "Austria"
}
]
});
</script>
Hãy tự mình thử »Ví dụ
Viết một hàng trong bảng cho mỗi thuộc tính trong một đối tượng:
<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>
Hãy tự mình thử »