iKey iKey - 12 days ago 5
AngularJS Question

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

//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. It refuses to work, but when you click the button again, everything is normal. I have no idea what is wrong.

Answer

Add $scope.$apply() to update the digest. 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();
}
Comments