[angularjs] foreach loop in angularjs

I was going through the forEach loop in AngularJS. There are few points that I did not understood about it.

  1. What is the use of the iterator function? Is there any way to go without it?
  2. What is the significance of the key and value as shown below?

angular.forEach($scope.data, function(value, key){});

PS: I tried to run this function without the arguments and it did not work.

Here's my json:

[
   {
     "Name": "Thomas",
     "Password": "thomasTheKing"
   },
   {
     "Name": "Linda",
     "Password": "lindatheQueen"
   }
]

My JavaScript file:

var app = angular.module('testModule', []);

app.controller('testController', function($scope, $http){
   $http.get('Data/info.json').then(
      function(data){
         $scope.data = data;
      }
   );

   angular.forEach($scope.data, function(value, key){
      if(value.Password == "thomasTheKing")
         console.log("username is thomas");
   });
});

Another question: Why the function above does not enter on if condition and print "username is thomas" in the console?

This question is related to angularjs foreach

The answer is


Questions 1 & 2

So basically, first parameter is the object to iterate on. It can be an array or an object. If it is an object like this :

var values = {name: 'misko', gender: 'male'};

Angular will take each value one by one the first one is name, the second is gender.

If your object to iterate on is an array (also possible), like this :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]

Angular.forEach will take one by one starting by the first object, then the second object.

For each of this object, it will so take them one by one and execute a specific code for each value. This code is called the iterator function. forEach is smart and behave differently if you are using an array of a collection. Here is some exemple :

var obj = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(obj, function(value, key) {
  console.log(key + ': ' + value);
});
// it will log two iteration like this
// name: misko
// gender: male

So key is the string value of your key and value is ... the value. You can use the key to access your value like this : obj['name'] = 'John'

If this time you display an array, like this :

var values = [{ "Name" : "Thomas", "Password" : "thomasTheKing" },
           { "Name" : "Linda", "Password" : "lindatheQueen" }];
angular.forEach(values, function(value, key){
     console.log(key + ': ' + value);
});
// it will log two iteration like this
// 0: [object Object]
// 1: [object Object]

So then value is your object (collection), and key is the index of your array since :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]
// is equal to
{0: { "Name" : "Thomas", "Password" : "thomasTheKing" },
 1: { "Name" : "Linda", "Password" : "lindatheQueen" }}

I hope it answer your question. Here is a JSFiddle to run some code and test if you want : http://jsfiddle.net/ygahqdge/

Debugging your code

The problem seems to come from the fact $http.get() is an asynchronous request.

You send a query on your son, THEN when you browser end downloading it it execute success. BUT just after sending your request your perform a loop using angular.forEach without waiting the answer of your JSON.

You need to include the loop in the success function

var app = angular.module('testModule', [])
    .controller('testController', ['$scope', '$http', function($scope, $http){
    $http.get('Data/info.json').then(function(data){
         $scope.data = data;

         angular.forEach($scope.data, function(value, key){
         if(value.Password == "thomasTheKing")
           console.log("username is thomas");
         });
    });

});

This should work.

Going more deeply

The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

You can give a look at deferred/promise APIs, it is an important concept of Angular to make smooth asynchronous actions.


In Angular 7 the for loop is like below

var values = [
        {
            "name":"Thomas",
            "password":"thomas"
        },
        { 
            "name":"linda",
            "password":"linda"
        }];

for (let item of values)
{
}

The angular.forEach() will iterate through your json object.

First iteration,

key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}

Second iteration,

key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }

To get the value of your name, you can use value.name or value["name"]. Same with your password, you use value.password or value["password"].

The code below will give you what you want:

   angular.forEach(json, function (value, key)
         {
                //console.log(key);
                //console.log(value);
                if (value.password == "thomasTheKing") {
                    console.log("username is thomas");
                }
         });

you have to use nested angular.forEach loops for JSON as shown below:

 var values = [
        {
            "name":"Thomas",
            "password":"thomas"
        },
        { 
            "name":"linda",
            "password":"linda"
        }];

    angular.forEach(values,function(value,key){
        angular.forEach(value,function(v1,k1){//this is nested angular.forEach loop
            console.log(k1+":"+v1);
        });
    });

Change the line into this

 angular.forEach(values, function(value, key){
   console.log(key + ': ' + value);
 });

 angular.forEach(values, function(value, key){
   console.log(key + ': ' + value.Name);
 });