【问题标题】:Data in callback when using 'Controller as' pattern in Angular在 Angular 中使用“Controller as”模式时回调中的数据
【发布时间】:2015-11-11 04:56:27
【问题描述】:

我有最简单的角度控制器:

tc.controller('PurchaseCtrl', function () {
    var purchase = this;
    purchase.heading = 'Premium Features';

    this.onSuccess = function (response) {
      console.log('Success', response);
      lib.alert('success', 'Success: ', 'Loaded list of available products...');
      purchase.productList = response;
    };
    this.onFail = function (response) {
      console.log('Failure', response);
    };

    console.log('google.payments.inapp.getSkuDetails');
    lib.alert('info', 'Working: ', 'Retreiving list of available products...');
    google.payments.inapp.getSkuDetails(
      {
        'parameters': {'env': 'prod'},
        'success': purchase.onSuccess,
        'failure': purchase.onFail
      });

  });

还有观点:

<div class="col-md-6 main" ng-controller="PurchaseCtrl as purchase">
    {{purchase}}
</div>

打印出来:

{"heading":"高级功能"}

我认为当回调返回时,视图将使用任何新数据进行更新。我错过了什么吗?回调返回,我在控制台中看到了 dtaa。

使用 $scope 模式,我认为我会使用 $scope.$apply 到异步方法,但我不知道如何在此处执行此操作。

【问题讨论】:

  • 您需要注入 $scope 并执行 scope.$apply 或以某种方式手动调用摘要循环,因为这些函数不是在 angular 的控制下运行的。但理想情况下,您可以将其抽象为角度服务并使用承诺模式创建延迟对象并避免执行范围。$apply

标签: angularjs callback angularjs-scope


【解决方案1】:

使用controllerAs 不会改变摘要循环的工作方式或任何东西。它只是向当前作用域添加一个属性(使用时名称与别名相同)的糖,其值指向控制器实例引用。因此,在这种情况下,您还需要手动调用摘要循环(使用scope.$apply[Asyc]() 甚至使用虚拟$timeout(angular.noop,0)$q.when() 等)。但是您可以通过将其抽象为角度服务并从那里返回一个承诺来避免注入范围,即

myService.$inject = ['$q'];
function myService($q){
  //pass data and use it where needed
  this.getSkuDetails = function(data){ 
     //create deferred object
     var defer = $q.defer();
     //You can even place this the global variable `google` in a 
     //constant or something an inject it for more clean code and testability.
     google.payments.inapp.getSkuDetails({
        'parameters': {'env': 'prod'},
        'success': function success(response){
            defer.resolve(response);// resolve with value
         },
        'failure': function error(response){
            defer.reject(response); //reject with value
         }
      });
     //return promise
     return defer.promise;
  }
}
//Register service as service

现在在您的控制器中注入myService 并将其用作:

   myService.getSkuDetails(data).then(function(response){
         purchase.productList = response;
   }).catch(function(error){
      //handle Error
   });

【讨论】:

  • 谢谢!这个控制器永远不会变大,对谷歌服务的调用只会在这里被调用,所以我跳过了实现该服务,但除此之外它工作得很好。
猜你喜欢
  • 2023-03-23
  • 2015-01-26
  • 2015-01-08
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
  • 2023-04-05
相关资源
最近更新 更多