1

Here's a unique array of account id and I want to call Ajax to retrieve the relevant accounts.

var account_id_unique = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"]; 

I decided to use a for loop and call AJAX inside the loop. However, instead of retrieving and storing different values to $scope.account = data;, I'm only storing the last value that I ran through the for loop. I tried to move $scope.account = data; to outside of the loop, but it's not possibly since I'm making Ajax call inside the loop. Is there a better way?

for (i=0; i<account_id_unique.length; i++){
    $http.get('api/accounts/'+ account_id_unique[i].toString())
        .success(function(data, status, headers, config){
         console.log(data);
         $scope.account = data;

    }).error(function(data, status, headers, config){
        console.warn(data);
    });

}; 

Additional: This is a snippet of html file. I'm trying to print out a list of accounts and artifacts to the front page.

SNS:{{ account.vendorCode }} identity id: {{account.identity.identityId}}
wag0325
  • 1,008
  • 5
  • 18
  • 34
  • 2
    You need to have an array where in each position 'i' of the array you can store the different values of 'data'. The array will have to be declared before the loop – Rafael Jul 07 '14 at 15:45
  • With Rafael's suggestion, note: [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Jonathan Lonowski Jul 07 '14 at 15:49

1 Answers1

0
$scope.account = "";
for (i=0; i<account_id_unique.length; i++){
    $http.get('api/accounts/'+ account_id_unique[i].toString())
        .success(function(data, status, headers, config){
         console.log(data);
         $scope.account = data;

    }).error(function(data, status, headers, config){
        console.warn(data);
    });

}; 
console.log("acccount is:" $scope.account);

OR if you want to store multiple values,

$scope.account = [];
for (i=0; i<account_id_unique.length; i++){
    $http.get('api/accounts/'+ account_id_unique[i].toString())
        .success(function(data, status, headers, config){
         console.log(data);
         $scope.account[i] = data;

    }).error(function(data, status, headers, config){
        console.warn(data);
    });

}; 
nikjohn
  • 20,026
  • 14
  • 50
  • 86
  • You're right about the console.log - I've removed it. It didn't serve much functional purpose anyway. Have also added an edit for the array situation.. Should work, I believe. – nikjohn Jul 07 '14 at 16:06