【问题标题】:Cant access a scope variable outside restangular request无法访问restangular请求之外的范围变量
【发布时间】:2014-09-30 06:27:22
【问题描述】:

rest api 在restangular get请求上返回一个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);
    });

【问题讨论】:

  • getList() 是异步的。回调外部的forEach()getList() 返回并填充$scope.users 之前运行。

标签: angularjs restangular


【解决方案1】:

阅读(更多)关于 angularjs 中的承诺。

then() 中的函数只有在 REST 请求返回响应后才会执行。

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

你可以这样做

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

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    相关资源
    最近更新 更多