Can't fully access the $ scope variables inside the strip callback?

I am having strange problems trying to integrate a strip into an angular project. I am running stripe methods inside my controller, and I want to update various region values ​​from a callback. I believe that there is a problem with the volume, which I do not understand. I can configure the console to log the variables of the area inside the callback, update them and the console log again to see the new values. However, if I try to write the variables outside the callback again, I will get the old values ​​and then the new values ​​will not be displayed in my view. I also tried moving my $ scope primitives to a $ scope object to no avail. Here is an example.

app.controller('checkoutCtrl', function ($scope) { // default values $scope.receipt = {}; $scope.paymentSuccess = false; $scope.saveCardForFuture = true; Stripe.card.createToken($scope.card, function (status, res) { $scope.receipt = res.data; $scope.paymentSuccess = true; if ($scope.saveCardForFuture === true) { // save card token } // tests cases console.log($scope.saveCard) //logs undefined console.log($scope.receipt) //logs the response data console.log($scope.paymentSuccess) //logs true }); // timeout long enough to wait for stripe response $timeout(function() { console.log($scope.receipt); //logs {} console.log($scope.paymentSuccess) //logs false }, 1000); }); 

Note: Stripe is not passed as a controller dependency, I just include it globally from my html index page. I have not yet found a way to include it as an injection addiction, but there should be a better way.

+6
source share
1 answer

You left the world of angularjs in a strip callback. Include a bock callback with $ scope. $ Apply (fn);

Good reading: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

 app.controller('checkoutCtrl', function ($scope) { // default values $scope.receipt = {}; $scope.paymentSuccess = false; $scope.saveCardForFuture = true; Stripe.card.createToken($scope.card, function (status, res) { $scope.$apply(function () { $scope.receipt = res.data; $scope.paymentSuccess = true; if ($scope.saveCardForFuture === true) { // save card token } // tests cases console.log($scope.saveCard) //logs undefined console.log($scope.receipt) //logs the response data console.log($scope.paymentSuccess) //logs true }); }); // timeout long enough to wait for stripe response $timeout(function() { console.log($scope.receipt); //logs {} console.log($scope.paymentSuccess) //logs false }, 1000); }); 
+10
source

Source: https://habr.com/ru/post/970317/


All Articles