2

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

Shayan Khan
  • 858
  • 2
  • 11
  • 35

2 Answers2

3

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

Community
  • 1
  • 1
Jamiec
  • 128,537
  • 12
  • 134
  • 188
2

Closures to rescue, your index which is not in sync with the with $scope.userActivity

for ($scope.index = 0; $scope.index < 5; $scope.index++){
    (function(i) {
        $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);
            });
    }($scope.index))
}
Thalaivar
  • 22,304
  • 5
  • 59
  • 68