繁体   English   中英

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

[英]Angular $scope variable not setting on callback

我无法弄清楚为什么未分配作用域变量。

<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以外,回调中的所有内容均有效。 它拒绝工作,但是当您再次单击该按钮时,一切正常。 我不知道怎么了。

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

尝试用$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一样

暂无
暂无

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

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