0

Is there way to access the scope from inside a foreach function in angular?

 $scope.getPlowHistory = function() {
       $scope.plowId = $stateParams.plowId;
       SnowPlowService.getPlowHistory($scope.plowId).then(function(response) {
            $scope.plow = response; 

            angular.forEach($scope.plow,function(value,index){
                $scope.Lat =  value.Latitude;
                $scope.Lng =  value.Longitude;                      
            });
        });
    };  

I would need $scope.Lat and $scope.Long to be usable in $scope.getPlowHistory() and not just inside the foreach loop.

Thanks!

6
  • $scope should be accessible, based on javascript closures, unless the scope is getting destroyed before the promise resolves. What error are you getting? Commented Jan 11, 2017 at 22:55
  • getting "undefined" when trying $scope.getPlowHistory = function() {... console.log($scope.Lat);}; outside the loop. Commented Jan 11, 2017 at 22:57
  • no problem accessing it, but you are overwriting the variables in each iteration of the loop. Commented Jan 11, 2017 at 22:59
  • true....how do I not do that? Commented Jan 11, 2017 at 23:03
  • you probably want an array Commented Jan 11, 2017 at 23:16

1 Answer 1

1

I don't 100% understand what you are trying to do, but something doesn't look right.

angular.forEach($scope.plow,function(value,index){
     $scope.Lat = value.Latitude;
     $scope.Lng = value.Longitude;                      
});

Your code is actually updating $scope.Lat and $scope.Lng with the value of the last element of your response.

What I think you are trying to do is something like this:

angular.forEach($scope.plow,function(value,index){
     $scope.Lat[index] = value.Latitude;
     $scope.Lng[index] = value.Longitude;                      
});

So if your result contains three elements, $scope.Lat and $scope.Lng will each contain three elements.

So to answer your original question, you are probably getting undefined because the results last element is empty for some reason.

I hope that this is what you are looking for, if not comment, and I will be happy to elaborate.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, it helped me understand variables in a loop.
@nrunit If my answer helped you, please mark it as an accepted answer to help build my reputation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.