0

This is my controller js, Here i am not able to get value from angular.forEach function, flagvalue not getting, Why?? Scope of flagvalue is end when foreach function ends??is that so??

var foreach = angular.module('foreach',[]);
  foreach.controller ('carcontroller', function($scope){
    alert("inn");
    $scope.carname = [{name:'polo'},{name:'BMW'},{name:'Audi'},{name:'Suzuki'}];
    var array = $scope.carname;
    $scope.addcar = function(){
      alert(" innn");
      var currentcarname = $scope.carname;
      alert(currentmoviename);
      angular.forEach($scope.carname,function(refer){   
        alert("in foreach loop");
        var flagvalue;
        alert(flagvalue);
        if(currentcarname.toLowerCase() == refer.name.toLowerCase()){
          alert("in foreach loop - if");
          flagvalue = true;
          return true;
        }
        alert(flagvalue);
        return true;
      });

      if(!flagvalue) {
        alert("in if again");   
      }
    };
  });

1 Answers1

0

Define the flag outside the forEach Loop.

 var  flagvalue;  
 angular.forEach($scope.carname, function(    refer    )
  {  
      if(currentcarname.toLowerCase() == refer.name.toLowerCase())
         {
           flagvalue    =   true;
            return    true;
         }
       return    true;

});
Divya MV
  • 2,021
  • 3
  • 31
  • 55
  • Thanx Divya:)its working now....can you explain, it will help me to get concept clear...is it releated with scope of var?? – sumit pethkar Mar 05 '15 at 08:43
  • @sumitpethkar this is purely a java script concept,when that variable is inside the foreach function it is local to that function and is not available outside the function.this is the very fundamental thing .Check out the link in the above comment.http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/ – Divya MV Mar 05 '15 at 09:39