Hướng dẫn AngularJS ng-repeat
Định nghĩa và cách sử dụng
ng-repeat
Hướng dẫn sẽ lặp lại một tập hợp HTML một số lần xác định.
Mỗi mục trong tập hợp HTML sẽ được lặp lại một lần.
Tập hợp phải là mảng hoặc đối tượng.
Lưu ý:Mỗi bản sao lặp lại sẽ nhận được một phạm vi riêng, được组成当前项目。
Nếu bạn có một tập hợp đối tượng:ng-repeat
Hướng dẫn rất phù hợp để tạo bảng HTML, hiển thị một hàng bảng cho mỗi đối tượng và hiển thị dữ liệu thuộc tính của mỗi đối tượng. Xem ví dụ dưới đây.
Mô hình
Ví dụ 1
Viết một tiêu đề cho mỗi mục trong mảng records:
<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>
Ví dụ 2
Viết một hàng bảng cho mỗi mục trong mảng records:
<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>
Ví dụ 3
Viết một hàng bảng cho mỗi thuộc tính của đố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>
Cú pháp
<element ng-repeat="biểu thức}}</element>
Tất cả các phần tử HTML đều hỗ trợ.
Tham số
Tham số | Mô tả |
---|---|
biểu thức |
Điều kiện lặp lại bộ sưu tập. Mẫu biểu thức hợp lệ:
|