AngularJS : assign asynchronous data to an array element in a for loop

I'm trying to assign array elements in a for loop with asynchronous results of a call to a ngResource action.

for ( var i = 0; i < projs.length; i++) {
    $scope.projets[i].redacteur = new Object(); // the Object where the result will be stored
    var param = new Object();
    param.email = projs[i].redacteurEmail;
    Agent.read(param, function(data) {
        $scope.projets[i].redacteur = data;
    });


}

The problem is : when the callback function is executed (when the data is received), i is out of bounds (it passed the last i++). Then the data received is assigned to a nonexistent object.

Any idea of a solution to this issue ?

Upvotes: 0

Views: 1327

Answers (3)

I solved this issue by putting the call to the callback function in a closure. With my example, it looks like that :

for (var i = 0; i < projs.length; i++) {
    $scope.projets[i].redacteur = new Object(); // the Object where the result will be stored
    var param = new Object();
    param.email = projs[i].redacteurEmail;
    (function(i) {
        Agent.read(param, function(data) {
            $scope.projets[i].redacteur = data;
        });
    })(i);
}

Upvotes: 2

Darryl
Darryl

Reputation: 1451

If I understand your issue correctly, I believe this may work.

myData = Agent.read(param, function() {
    $scope.projets[i].redacteur = myData;
});

This is the approach I have used. I'm still new to Angular, but my understanding is that myData becomes a deferred promise. As a deferred promise it must be resolved prior to use. Please, someone who has more experience Angular and deferred promises chime in.

Upvotes: 0

yotamsha
yotamsha

Reputation: 384

I had a similar issue, and I solved it by using Promises. The basic idea is that I send the index of the array as a parameter to my asynchronous request callback, and then I can handle it when the response arrives. Hope that helps.

Upvotes: 0

Related Questions