Shayan Khan Shayan Khan - 1 month ago 11
AngularJS Question

How to pass an incremental index value to $http.get

How do I pass an incremental value into the $http.get function. See below for code snippet:

for($scope.index=0 ; $scope.index < 5 ; $scope.index++)

{
$http.get('/api/post', {params: { id: $scope.userActivity[$scope.index].post }})
.success(function(res){
console.log('The value for index is: ' + $scope.userActivity[$scope.index]);
})
.error(function(data, status){
console.log(data);
});
}
})


I am getting "The value for index is: undefined" and it is driving me nuts!

Thanks

Answer

The problem is that by the time your first (and in fact all) your success callbacks fire $scope.index will have the value 5 which is presumably outside of the range of $scope.userActivity array.

One way to solve this is to use an IIFE

for($scope.index=0 ; $scope.index < 5 ; $scope.index++)

    {
      (function(i){
        $http.get('/api/post', {params: { id: $scope.userActivity[i].post }})
            .success(function(res){
                console.log('The value for index is: ' + $scope.userActivity[i]);
            })
            .error(function(data, status){
                console.log(data);
            });
        }
      })
    })($scope.index);
  }

This other StackOverflow Q/A will give you more in-depth detail: JavaScript closure inside loops – simple practical example