คำอธิบาย
ฟังก์ชัน forEach() ใน AngularJS ใช้ Iterator Object เพื่อวนลูปผ่าน Collection ของ Items, Objects หรือ Array ฟังก์ชัน Iterator จะถูกเรียกพร้อมพารามิเตอร์ (value, key, obj) โดยที่:
- value - ค่าของ Object Property หรือ Array Element
- key - Key ของ Property หรือ Index ของ Array
- obj - Object ทั้งหมด
หมายเหตุ: forEach() ไม่วนลูปผ่าน Inherited Properties
Syntax
angular.forEach(obj, iterator, [context])
ตัวอย่าง - วนลูปค่าด้วย forEach()
สร้างไฟล์ forEach.html ในโฟลเดอร์โปรเจกต์ Angular:
<!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>
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>
ผลลัพธ์
แสดงรายชื่อพนักงาน: John, Steve, Bill, Clark, Tim โดยใช้ ng-repeat วนลูปแสดงผลจาก Array ที่สร้างโดย forEach
หมายเหตุ: AngularJS (v1.x) หยุดพัฒนาแล้ว ควรย้ายไปใช้ Angular (v2+) หรือ Framework สูงสุด