1

I want to iterate over a loop and call a service (which is asynchronus) for each item -

 for(var i=0;i<$scope.objs.length;i++) {
        var obj= $scope.objs[i];            
        api.invoke({
            //parameters
        }).then(function (members) {
            $scope.setInfo(obj.name,members);   
        }, function (fail) {
            console.log("failed");
        });  
    }   

But, as it is asynchronus , obj value is getting ovrewritten before I can send it to the method - setInfo(). How can I avoid it?

4
  • 1
    it would be be better to avoid calling api in a loop Commented May 27, 2015 at 9:13
  • i have to cal api for each array object. How can I do it then? (if not loop) Commented May 27, 2015 at 9:18
  • pass array of input to server.. get array of responses Commented May 27, 2015 at 9:21
  • You can pass array of objects in $scope.setInfo and let api call each time and you can obviously put a loop inside defination of setInfo() Commented May 27, 2015 at 9:21

1 Answer 1

1

You could achieve this by using angular.forEach which would have value that will be available for that particular function level.

Code

angular.forEach($scope.objs, function(value, index) {
    api.invoke({
        //parameters
    }).then(function(members) {
        $scope.setInfo(value.name, members);
    }, function(fail) {
        console.log("failed");
    });
})

OR same thing can be done by creating anonymous function.

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

Comments

Your Answer

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