Angularjs 无法访问restangular请求之外的作用域变量

Angularjs 无法访问restangular请求之外的作用域变量,angularjs,restangular,Angularjs,Restangular,restapi在restangularget请求中返回一个json对象,响应只能在函数内部访问 Restangular.all('getUsers').getList().then(function(response) { $scope.users = response; angular.forEach($scope.users, function(value, key) { //This works console.log(key + ': ' + va

restapi在restangularget请求中返回一个json对象,响应只能在函数内部访问

 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);
    });
阅读(更多)angularjs中的承诺

then()中的函数仅在REST请求返回响应后执行

下面的代码将在发送请求后立即运行,但肯定是在处理响应之前运行

你可以

$scope.$watch("users", function() {
   angular.forEach($scope.users, function(value, key) {    //This does now work
           console.log(key + ': ' + value);
       });
});
getList()
是异步的。回调外部的
forEach()
getList()
返回并填充
$scope.users
之前运行。