Using AngularJS forEach() Function in AngularJS with Example

We are going to discuss Angular.forEach function. Angular has a very rich API with many functions and directives. forEach is a function reside in ng Module. forEach invokes the iterator function for each item in an array or object. It is similar to for in in JavaScript. for in is used for objects while forEach can be used for both arrays and objects. Also, using forEach will be more convenient if you are using Angular for your application logic as it will maintain the consistency of the code.

Using Angular forEach() with an Array

In this tutorial, we will be creating a small application which will use Angular.forEach function.

What we do in this application, we will have an Array of objects Like this

[
{ name: 'Adam', marks : '75', grade : 'P' },
{ name: 'Mike', marks : '45', grade : 'F' },
{ name: 'Dino', marks : '85', grade : 'P' },
{ name: 'Anna', marks : '35', grade : 'F' },
{ name: 'Lucy', marks : '80', grade : 'P' }
]Code language: JavaScript (javascript)

We want to print the students who have passed the exam and who have failed the exam separately. It can easily be done with forEach as forEach allows us to write functions for each element in the array easily. So, forEach iterates over every object in the list, then it will add the student names to two separate arrays depending on the status of the grade. Let’s start coding it.

You might check it :

**Add AngularJs in your application.**

First, you have to get AngularJs library to your application before using it. This can be done in two ways.

1. You can use a CDN for this.

There are performance benefits in using a CDN. You can find a list of CDN links

https://cdnjs.com/libraries/angular.js/Code language: JavaScript (javascript)

2. Use Angular.js file application as an external file.

You can download AngularJs from the official site and include it in your application.

In this application, I will use the google CDN. Then you have to add it into the script tag which is inside the head tag of the web page.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js" > </script>Code language: HTML, XML (xml)

Next, we are going to implement the logic part. See the following code.

<script>
var myApp = angular.module('myApp', []);
myApp.controller('myController', ['$scope', function ($scope) {
$scope.list = [
{ name: 'Adam', marks : '75', grade : 'P' },
{ name: 'Mike', marks : '45', grade : 'F' },
{ name: 'Dino', marks : '85', grade : 'P' },
{ name: 'Anna', marks : '35', grade : 'F' },
{ name: 'Lucy', marks : '80', grade : 'P'}];

$scope.submit = function (list) {
var passStudents = [];
var failStudents = [];
angular.forEach(list, function (value, key) {
if(value.grade =="P")
passStudents.push(value.name);
else
failStudents.push(value.name);
});
if (passStudents.length > 0)
$scope.pass_list = passStudents.toString();
if (failStudents.length > 0)
$scope.fail_list = failStudents.toString();
}
}]);
</script>Code language: PHP (php)

This is the script code of the application. Place this Script code at bottom of the body.

So, what does it do here?

First, we create an Angular module with `myApp` which we will use later in the View.

Then we will access a controller called myController for it.


Then we write a submit function which will be called inside the view area. Inside the function, we create two arrays called passStudents and failedStudents. This is to hold names of students who have passed the exam and who have failed the exam.

Then we use forEach function to iterate over the list. forEach takes each array element separately, then checks whether the grade is equal to P. If yes, then pass the names of that student to the passStudents array. Otherwise, push the name to the failedStudents array. Then we convert the arrays into strings and assign them to scope variables called pass_list and failed_list, which will be used by the view.

Code for the view is as follows.

<div ng-app="myApp" ng-controller="myController">
<p>Pass Students{{submit(list)}}</p>
<p style="padding-left: 20px">{{pass_list}}</p>
<p>Failed Students</p>
<p style="padding-left: 20px">{{fail_list}}</p>
</div>Code language: HTML, XML (xml)


If you have used Angular before, you may know that the ng-app attribute must be specified, and your Angular code must be placed inside the tags for which you defined the ng-app attribute.

The submit(list) function will be called at the page loading, and then Angular expressions such as {{pass_list}} and {{failed_list}} will be executed.

Notice that you have not used the ‘key’ attribute here. When forEach iterates over an array, ‘key’ represents the position of the item in the array.

```passStudents.push(value.name);```
if you replace this line with 
```passStudents.push(key);```
you get the array index of each Student.Code language: JavaScript (javascript)

See Live Example

Using Angular forEach() with an Object


We earlier said that we can use forEach with both arrays and objects. In our next example, we will have a Student list as an Object. This will help you grasp the concept of ‘key’ better. Let’s do it now.

This is the object we are going to use for the Students.

{
Adam : {marks : '75', grade : 'P'},
Mike : {marks : '45', grade : 'F'},
Dino : {marks : '85', grade : 'P'},
Anna : {marks : '35', grade : 'F'},
Lucy : {marks : '80', grade : 'P'}
}Code language: CSS (css)

We will change our business logic according to the current object.

<script>
var myApp = angular.module('myApp', []);
myApp.controller('myController', ['$scope', function ($scope) {
$scope.list = {
Adam : {marks : '75', grade : 'P'},
Mike : {marks : '45', grade : 'F'},
Dino : {marks : '85', grade : 'P'},
Anna : {marks : '35', grade : 'F'},
Lucy : {marks : '80', grade : 'P'}
};
$scope.submit = function (list) {
var passStudents = [];
var failStudents = [];
angular.forEach(list, function (value, key) {
if (value.grade == "P")
passStudents.push(key);
else
failStudents.push(key);
});
if (passStudents.length > 0)
$scope.pass_list = passStudents.toString();
if (failStudents.length > 0)
$scope.fail_list = failStudents.toString();
}
}]);
</script>Code language: PHP (php)


Notice the differences. The list object has 5 objects inside it. When forEach iterates over the list object, it will take each of these sub-objects. So, the ‘key’ will be student names such as Adam, Mike. The ‘value’ will be the objects that represent those student names. You can see that if the value.grade equals to ‘P’, then it pushes the key to pass_list.

Next, two lists will be displayed on the webpage with the following code.

<div ng-app="myApp" ng-controller="myController">
<p>Pass Students{{submit(list)}}</p>
<p style="padding-left: 20px">{{pass_list}}</p>
<p>Failed Students</p>
<p style="padding-left: 20px">{{fail_list}}</p>
</div>Code language: HTML, XML (xml)

See Live Example

Conclusion

We have discussed the main two uses of the forEach function in the Angular API. There is one more important point to be mentioned. forEach does not throw a TypeError for objects with ‘undefined’ and ‘null’ values. Instead, it will return the provided value.

  • Puspesh Deolal

    I am a passionate coding enthusiast with a strong desire to contribute to the world through sharing and expanding my knowledge. In 2022, I successfully completed my MCA from Uttarakhand Open University, equipping me with a solid foundation in computer science. My expertise extends to various programming languages including Python, HTML, CSS, JS, React, C++, C, Android Programming, and JAVA. I am constantly seeking opportunities to enhance my skills and stay at the forefront of technological advancements.

    View all posts

Leave a Comment