简体   繁体   English

角度$ scope变量未在回调中设置

[英]Angular $scope variable not setting on callback

I can't figure out why the scope variable is not being assigned. 我无法弄清楚为什么未分配作用域变量。

<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 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();
}

Everything in the callback works except for assigning the reference to $scope.txref. 除了将引用分配给$ scope.txref以外,回调中的所有内容均有效。 It refuses to work, but when you click the button again, everything is normal. 它拒绝工作,但是当您再次单击该按钮时,一切正常。 I have no idea what is wrong. 我不知道怎么了。

Add $scope.$apply() to update the digest. 添加$scope.$apply()以更新摘要。 This should fix your issue. 这应该可以解决您的问题。 Also initiate your scope variable: 还启动您的范围变量:

$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();
}

try to wrap your variable assignment with $timeout for example, to notify angular about your change: 尝试用$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
     });   
 },

and do not forget to inject $timeout to your controller, the same way as $scope is injected 并且不要忘记将$ timeout注入到控制器中,就像注入$ scope一样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM