Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Braintree Drop in callback and Angular $scope doesn't work

I am trying to utilize the braintree drop in UI within an angular controller eg.

https://jsfiddle.net/6jmkwode/

function PaymentCtrl($scope) {
    $scope.hasCalledBack = 'Nope';

    braintree.setup('BRAINTREE_KEY',
        'dropin', {
        container: 'dropin',
        onPaymentMethodReceived: function (obj) {
            $scope.hasCalledBack = 'YEP!';
            alert('Did the scope variable change? No? Well it should have....');
        }
    });
}

However the $scope.hasCalledBack never changes in the callback even thought the alert fires.

like image 939
Josh Stuart Avatar asked Aug 21 '26 12:08

Josh Stuart


1 Answers

Simply wrap your callback code with $scope.$apply() (nice article about it):

...
onPaymentMethodReceived: function (obj) {
    $scope.$apply(function() {
        $scope.hasCalledBack = 'YEP!';
        alert('Did the scope variable change? Yes!');
    });
}
...

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.

See updated Demo.

like image 98
Ilya Luzyanin Avatar answered Aug 24 '26 01:08

Ilya Luzyanin