0

I am learning JavaScript and AngularJS. I want to use the values that are outside of function, but I don't know how to access them.

Here is my code (AngularJS Controller):

var init = function() {
    $http.get('getSomeValues').then(function (res) {
        var returnArray = res.data; // Result is array

        for(var i=0; i < returnArray.length; i++) { // Loop through the array
            console.log("THIS WORKS FINE: ", returnArray[i].value); // It works
            $http.get('getOtherValues/' + returnArray[i].value).then(function (res) {
                console.log("WHAT'S IN IT: ", returnArray[i].value); // Shows 'undefined' error
            });
        }
    });
};
init();

So basically I want to access the array returnArray, but I can't. Is there any good way to access the values? I assume that '.then(function ..' causes error..

Kimchi Man
  • 1,131
  • 3
  • 13
  • 24
  • 1
    Read about JavaScipt Closures. http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Dmitry Volokh Jul 23 '14 at 14:10
  • You can use res. If you need what you sent in returnArray[i], you can repost it back in res by modifying getOtherValues code – Robert Jul 23 '14 at 14:10

1 Answers1

2

You'll need to use a IIFE:

Replace:

for(var i=0; i < returnArray.length; i++) { // Loop through the array
    $http.get('getOtherValues/' + returnArray[i].value).then(function (res) {
        console.log("WHAT'S IN IT: ", returnArray[i].value); // Shows 'undefined' error
    });
}

With:

for(var i=0; i < returnArray.length; i++) { // Loop through the array
    (function(data){
        $http.get('getOtherValues/' + data.value).then(function (res) {
            console.log("WHAT'S IN IT: ", data.value); // Shows 'undefined' error
        });
    }(returnArray[i]))
}

This ensures that, for the current iteration of the for loop, the data variable will be set to the current raturnArray item.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • 1
    this is elegant answer – Medet Tleukabiluly Jul 23 '14 at 14:14
  • @Cerbrus Oh I mean that could you explain the error from my original code – Kimchi Man Jul 23 '14 at 14:26
  • 1
    The problem was that the loop continued before the `get` could finish. That caused `i` to be something it shouldn't have been, in the `returnArray[i]`'s. In case this answer provided the solution for you, could you consider accepting my answer, please? – Cerbrus Jul 23 '14 at 14:42