Hàm forEach() trong AngularJS dùng đối tượng Iterator để lặp qua tập hợp các mục (items), đối tượng hoặc mảng. Hàm iterator được gọi với iterator object (value, key, obj) trong đó:
- value: giá trị thuộc tính đối tượng hoặc phần tử mảng,
- key: khóa thuộc tính đối tượng hoặc chỉ số phần tử mảng,
- obj: toàn bộ đối tượng.
Lưu ý: forEach() không lặp qua các thuộc tính kế thừa (inherited properties).
Cú pháp
angular.forEach(obj, iterator, [context])
Ví dụ – Lặp giá trị bằng forEach()
Tạo file "forEach.html" trong thư mục dự án Angular và dán mã sau:
<!DOCTYPE html>
<html>
<head>
<title>angular.forEach()</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">
</script>
</head>
<body ng-app="app" ng-cloak style="padding:30px">
<h1 style="color:green">
Welcome to Tutorials Point
</h1>
<h2>AngularJS | angular.forEach()</h2>
<p>Employee Names:</p>
<div ng-controller="demo">
<div ng-repeat="name in names">
<ul><li>{{name}}</li></ul>
</div>
</div>
<!-- Script xử lý -->
<script>
var app = angular.module("app", []);
app.controller('demo', ['$scope', function ($scope) {
$scope.names = [];
var values = [{name: 'John'},
{name: 'Steve'},
{name: 'Bill'},
{name: 'Clark'},
{name: 'Tim'}];
angular.forEach(values, function (value, key) {
$scope.names.push(value.name);
});
}]);
</script>
</body>
</html>
Kết quả đầu ra
Danh sách tên nhân viên (John, Steve, Bill, Clark, Tim) được hiển thị trên giao diện nhờ ng-repeat lặp qua mảng $scope.names được điền bởi angular.forEach().