I'm running into strange issues trying to integrate stripe in an angular project. I'm running the stripe methods inside my controller and I want to update various scope values from the callback. I believe there is some scope issue I'm not understanding. I can console log my scope variables inside the callback, update them and console log again to see the new values. However if I try to log the variables again outside of the callback I get the old values and then new values are not making it into my view. I've also tried moving my $scope primitives to a $scope object to no avail. Here's 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 haven't yet found a way to include it as an injectable dependency but there must be a better way.
You left the angularjs world in the stripe callback. Enclose the callback bock with $scope.$apply(fn);
Some 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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With