Search code examples
angularjsrestangular

Cant access a scope variable outside restangular request


The rest api returns a json object on restangular get request and the response is only accessible inside the function

 Restangular.all('getUsers').getList().then(function(response) {
    $scope.users = response;
    angular.forEach($scope.users, function(value, key) {    //This works
        console.log(key + ': ' + value);
    });
  });

  angular.forEach($scope.users, function(value, key) {    //This does not work
        console.log(key + ': ' + value);
    });

Solution

  • Read (more) about promises in angularjs.

    The function inside the then() is executed only after the REST request has returned a response.

    The code below that is run immediately after the request has been send, but definitely before the response has been processed.

    You could do

    $scope.$watch("users", function() {
       angular.forEach($scope.users, function(value, key) {    //This does now work
               console.log(key + ': ' + value);
           });
    });