Hit enter after type your search item

Angular forEach explained with 2 examples

The forEach function in AngularJS

The Angular forEach function can be used to perform some action for each item in a given object or array. The iterator function in forEach is invoked for each item of array or object.

forEach Array example Display index/values by forEach

This is almost similar to the foreach loop in other programming languages like JavaScript,  PHP etc. where foreach loop is used with arrays or other collections. In AngularJS, it is a little different, however, it iterates through each element of the given array or object.

Syntax of using forEach function

Following is the way to use the forEach function of AngularJS:

angular.forEach(object_or_Array, iterator, [context]);

Where the first parameter can be an object or an array. The second parameter is an iterator function that is invoked for each item in object or array.

See the examples in the following section for learning more about forEach Angular function.

A demo of using forEach with an array

In this example, an array is created with three elements in the controller part of Angular. The forEach is used with that array and employee names are assigned to a variable. The employee names are displayed in a div element as web page loads:

angular forEach

See online demo and code

The code:

An example of forEach for displaying index and values

In this example, the index and values of the array are displayed by using the forEach function of AngularJS. As you click the button, the keys and values of the array will display in the div element, unlike above example where only the values are displayed.

angular forEach index value

See online demo and code

The code:

You can see in the controller section, an array with three elements is created. This is followed by using a forEach function where that array element is used along with its value and key. The values of index and values of elements are used in the next line for gathering the information of each element in the content variable.

In the markup section, a div is used where “content” is given that contains the string with key/value pairs of the array. On the click event of the button, the ng-click directive is used.

This div height required for enabling the sticky sidebar