I'm trying to iterate through an array of objects and call a service to get
information for each. The service returns a promise. However, the issue I
have is the asynchronous nature of the service call. How should I be
implementing this? The below is generally the idea I want, but the problem
is that I'm trying to reference variables from the outer scope which are
set differently by the time the then() part of the promise is processed
(e.g., when I reference $scope.stuff[i].data, the i variable is incremented
to one past the end of the array). What I would normally do in other
frameworks (or plain JavaScript) is pass a context (in this case, i) to the
service and expect it to pass it to me in the callback (the then() part of
the promise).
app.controller("Controller", ["$scope", "MyService",
function($scope,MyService)
{
$scope.stuff = new Array();
$scope.stuff.push(
{
name: "First thing I'm collecting data on",
id: 1384,
data: new Array()
});
$scope.stuff.push(
{
name: "Second thing I'm collecting data on",
id: 34839,
data: new Array()
});
for (var i = 0; i < $scope.stuff.length; i++)
{
MyService.getData($scope.stuff[i].id).then(
function(data)
{
$scope.stuff[i].data = data;
});
}
}]);
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.