ng-repeatChỉ thị AngularJS


Thí 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>

Định nghĩa và Cách sử dụng

Lệnh ng-repeatlặp lại một tập hợp HTML, một số lần nhất định.

Tập hợp HTML sẽ được lặp lại một lần cho mỗi mục trong một 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 trường hợp lặp lại được cung cấp phạm vi riêng của nó, 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, ng-repeatchỉ thị này rất phù hợp để tạo một bảng HTML, hiển thị một hàng 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ụ bên dưới.


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

x in records track by $id(x)


Các ví dụ khác

Thí dụ

Viết một hàng 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>

Thí dụ

Viết một hàng 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>