AngularJS – forEach() function

PythonServer Side ProgrammingProgramming

The forEach() function in AngularJS uses the Iterator object to iterate over the collection of items or objects or an array. The iterator function is called with the iterator object(value, key, obj) where,

  • value represents the object property or an array element,
  • key specifies the object property key or array element index, and
  • obj represents the whole object.

Note that the forEach() function does not iterate over the inherited properties.

Syntax

angular.forEach(obj, iterator, [context])

Example − Iterate the values using forEach()

Create a file "forEach.html" in your Angular project directory and copy-paste the following code snippet.

<!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 for passing the values and checking... -->
      <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>

Output

To run the above code, just go to your file and run it as a normal HTML file. You will see the following output on the browser window.

When the values are not equal −

raja
Updated on 08-Oct-2021 10:41:45

Advertisements