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

Sean
  • 1,151
  • 3
  • 15
  • 37

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
  • 133,658
  • 13
  • 134
  • 193
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
  • 23,282
  • 5
  • 60
  • 71
  • Thanks for the answer mate. As I said in the comment above, it did the trick. Highly appreciated – Sean Oct 24 '16 at 16:07