Angular $ scope变量未在回调上设置

时间:2016-11-23 14:46:13

标签: javascript angularjs

我无法弄清楚为什么没有分配范围变量。

<script src="https://js.paystack.co/v1/inline.js"></script>
<button type="button" ng-click="checkout()">Checkout</button>
<div ng-show='txref'>
   <h2>Payment successful!</h2> Transaction reference: {{txref}}
</div>

JS

 //this function triggers when the button above is clicked. Everything else except assigning the reference to $scope.txref
$scope.checkout = function() {
   var handler = PaystackPop.setup({
     key: 'pk_test_1c828c1b8d9a98232c90d7aa6c418953c8150096',
     email: 'customer@email.com',
     amount: 10000 * 100,
     ref: Math.floor((Math.random() * 100000) + 1),
     callback: function(response){
         console.log(response.reference)  //works
         alert(response.reference)  //works
         $scope.txref = response.reference; //doesn't work until you click the button again
     },
     onClose: function(){
         alert('window closed');
      }
   });
   handler.openIframe();
}

回调中的所有内容都有效,除了将引用分配给$ scope.txref。它拒绝工作,但当你再次点击按钮时,一切正常。我不知道出了什么问题。

2 个答案:

答案 0 :(得分:1)

添加$scope.$apply()以更新摘要。这应该可以解决您的问题。同时启动范围变量:

$scope.checkout = function() {
   $scope.txref = '';
   var handler = PaystackPop.setup({
     key: 'pk_test_1c828c1b8d9a98232c90d7aa6c418953c8150096',
     email: 'customer@email.com',
     amount: 10000 * 100,
     ref: Math.floor((Math.random() * 100000) + 1),
     callback: function(response){
         console.log(response.reference)  //works
         alert(response.reference)  //works
         $scope.txref = response.reference;
         $scope.$apply(); // <---- This should do the work for you
     },
     onClose: function(){
         alert('window closed');
      }
   });
   handler.openIframe();
}

答案 1 :(得分:-1)

尝试用$timeout包装您的变量赋值,以通知angular您的更改:

callback: function(response){
     console.log(response.reference)  //works
     alert(response.reference)  //works
     $timeout(function () {
       $scope.txref = response.reference; //doesn't work until you click the button again
     });   
 },

并且不要忘记将 $ timeout 注入您的控制器,就像注入 $ scope 一样