angularjsiterationrestangular

Index value is not recognized in RestAngular


When I fire an rest API call in an iteration then index value is not recognized inside the block. Refer code snippet:

$scope.user = [];
var userList = [{'id':1, 'name':'Joe'}, {'id':2, 'name': 'Jack'}];
for (var i=0; i<userList.length; i++) {
  Restangular.all('userInfo/userId' + userList[i].id).getList().then(function(users) {
    // returns given user information
    console.log(i);
    $scope.user.push({'id': userList[i].id, 'info': users});
  })
}

Got the following error

Uncaught TypeError: Cannot read property 'i' of undefined 

How to resolve this?


Solution

  • Try This.

    This is called closure inside loop.

        $scope.user = [];
        var userList = [{'id':1, 'name':'Joe'}, {'id':2, 'name': 'Jack'}];
        for (var i=0; i<userList.length; i++) {
          function(index){
              Restangular.all('userInfo/userId/'+userList[index].id).getList().then(function(users) {
              // returns given user information
              console.log(index);
              $scope.user.push({'id': userList[index].id, 'info': users});
          })(i);
        }
    }