当回调调用时,AngularJS不会更新

时间:2017-05-09 15:13:21

标签: javascript angularjs

当我在回调中更新AngularJS变量时controller没有更新我的观点时,我遇到了一个奇怪的问题:

payment.controller.js

(function () {
  'use strict';
  //TODO: Declare the Cover module
  angular.module('payment', []);

  //TODO: Declare the controller of Cover module
  angular.module('payment').controller('PaymentController', function factory() {
    var _this = this;

    _this.pay = event => {
      event.preventDefault();
      if(_this.Card.Expiration != null && _this.Card.CVC != null && _this.Card.CardNumber != null){
        Stripe.card.createToken({
          number: _this.Card.CardNumber,
          cvc: _this.Card.CVC,
          exp_month: _this.Card.Expiration.split('/')[0],
          exp_year: _this.Card.Expiration.split('/')[1]
        }, myFunc);

        // This doesn't work
        function myFunc(){
          _this.ErrorMessage = 'Error';
        };

        // But this does
        myFunc();
      } else {
        _this.ErrorMessage = 'Check the card data please';
      }
    };
  }
})();

route.js

.when('/payment',{
  templateUrl: 'pay/pay.html',
  controller:'PaymentController',
  controllerAs: 'payment'
})

pay.html (相关位)

<div class="form__errors" ng-show="payment.errorFlag">
  <p>{{payment.ErrorMessage}}</p>
</div>

_这是在范围内,我可以看到它在控制台中更新。我正在运行Angular 1.6.

1 个答案:

答案 0 :(得分:1)

当回调更新了您的组件模型时,您需要致电$scope.$appy()

$scope注入您的控制器,并在$scope.$apply()中致电myFunc