Nigel Johnson
Nigel Johnson

Reputation: 522

How do I disable a button until callback is called?

I have a contact form with a button that I want to disable if the form is not valid or a recaptcha is not selected.

<form name="contactForm" data-ng-controller="ContactCtrl" novalidate>
...
<input class="form-control" name="email" type="email" required data-ng-model="contactEmail">
...
<div class="g-recaptcha" data-callback="recaptchaCalled" data-expired-callback="recaptchaExpired" data-sitekey="PULBIC KEY"></div>
...
<input type="checkbox" data-ng-model="recaptchaValid" />
...
<button type="submit" ng-disabled="!recaptchaValid || !contactForm.$valid">Send</button>

This is the controller for the form, and now this callback is being called because the alert happens.

app.controller('ContactCtrl', function($scope) {
    $scope.recaptchaValid = false;
    recaptchaCalled = function() {
        $scope.recaptchaValid = true;
        alert('pressed!');
    };
});

If I enter a valid email address, the button stays disabled (and checkbox unchecked), I can then click the checkbox and the button enables, uncheck and disables again. - correct behaviour.

If I enter a valid email address and then do the captcha, the button stays disabled (and checkbox unchecked).

If I do the captcha and then enter a valid email the button enables (and checkbox is checked).

If I enter a valid email address and then do the captcha, and then go back and touch the form and force it to revalidate, the button (and checkbox) correctly do their thing.

This seems to indicate there is a refresh that needs to be called. I can't get this up on jsfiddle as I can't get angular working.

I did find this: https://github.com/VividCortex/angular-recaptcha and this on how to integrate it: http://code.ciphertrick.com/2015/05/19/google-recaptcha-with-angularjs/ but its way over the top and I can't work out the bits I need.

Upvotes: 1

Views: 1233

Answers (1)

Jeffrey
Jeffrey

Reputation: 2005

After you receive the callback and set the variable in your controller you have to call the $apply() function. Because the callback is from outside Angular, Angular does not know that it needs to update, so you will have to tell it to do so. Now you can use ngDisabled on your button and have it linked to a variable in your controller and you're done.

Upvotes: 1

Related Questions