Dan Ward
Dan Ward

Reputation: 141

$scope.$apply in AngularJS - Function executed each time is the last defined function

If I call the code below inside a loop of asynchronous HTTP requests I get latter response. Any suggestions on where I could be going wrong?

NOTE: This is essentially pseudo code.

function successful_request(site) {
    console.log('In: ' + site.id);
    $scope.$apply(function() { console.log('Out: ' + site.id); }
}

OUTPUT:

In: 1
In: 2
In: 3
Out: 3
Out: 3
Out: 3

I hope I've made sense here. I suspect it's a case of how I'm calling $scope.$apply but I'm not sure what I should do differently.

Upvotes: 1

Views: 101

Answers (2)

callmehiphop
callmehiphop

Reputation: 646

This kind of side effect is fairly common when running a closure inside of a loop, I can't really tell from your example but you may want to take a look through the following link to see if it applies to your situation. JavaScript closure inside loops – simple practical example

Upvotes: 0

Joe Minichino
Joe Minichino

Reputation: 2773

It looks to me as if you declared the variable site globally / outside of the asynchronous loop scope.

Upvotes: 1

Related Questions