sumit pethkar sumit pethkar - 3 months ago 12
Javascript Question

not able to get value from angular.forEach function,flagvalue not getting,Why?

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");
}
};
});

Answer

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;

});