匿名函数中的$ scope

时间:2014-07-28 22:11:33

标签: angularjs asynchronous scope anonymous

我有以下内容:

app.controller('MyController', function($scope, MyAdapter) {       
   MyAdapter.getContactInfo(123, function(response) {
      $scope.contactInfo = JSON.parse(response.result);
   });        
}

app.service("MyAdapter", function() {
    this.getContactInfo = function(id, callback) {          
        thirdPartyAPI(id, callback);            
    };
});

本质上我的控制器调用服务来调用第三方api中的异步函数。我需要使用响应来更新控制器中的作用域,但似乎我无法从匿名函数访问作用域。有办法解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

您应该有权访问回调中的范围。可能发生的是因为它是更新范围的第三方异步调用,angular不知道它。您需要使用$scope.$apply()来触发摘要周期。

app.controller('MyController', function($scope, MyAdapter) {       
   MyAdapter.getContactInfo(123, function(response) {
      $scope.contactInfo = JSON.parse(response.result);
      $scope.$apply();
   });        
}
相关问题