Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS "ng-submit" has problems when the browser pre-populates form fields?

I'm fairly new to AngularJS, and am experimenting with a single-page application having a "login" form. The form is bound by "ng-submit", and its controller makes an AJAX call returning a token if authentication was successful. Subsequent AJAX calls pass this token. (No, I DON'T want to use basic auth, because I want a non-hacky "logout" button).

I have setup my username and password fields with "required", so that AngularJS will display a tooltip when users try to submit the form with a blank value in a field:

<form name="loginForm" ng-submit="login()">
    <fieldset>
        <legend>Sign In</legend>
        <label>Email</label>
        <input name="loginEmail" type="text" placeholder="Registered email address…" ng-model="loginEmail" required>
        <label>Password</label>
        <input name="loginPassword" type="password" placeholder="Password…" ng-model="loginPassword" required>
        <br/>
        <button type="submit" class="btn">Login</button>
    </fieldset>
</form>

The issue arises when some browsers (Firefox, at least) asks whether the user wants the browser to remember the username and password, and pre-populate it next time.

When the browser populates either of these fields, AngularJS basically stops working. The "ng-submit"-bound form will not submit... the bound controller function isn't invoked at all. My first thought was that the pre-populated fields didn't trigger an event, so AngularJS thinks they're still blank. However, there are no tooltips popping up to warn about blank fields. It's like AngularJS just completely shut down.

Strangely, as soon as you make ANY manual edit to either field, AngularJS comes back to life... validation tooltips and form submission start working again.

Is there a bug here, or is the problem with lack of knowledge on my end? How can you make AngularJS recognize browser-populated fields? Or if there are problems in this area, how can you prevent the browser from pre-populating fields so they don't interfere with AngularJS?

like image 330
Steve Perkins Avatar asked Jun 20 '13 12:06

Steve Perkins


2 Answers

$(window).load(function() {
  // updates autofilled fields
  window.setTimeout(function() {
    $('input[ng-model]').trigger('input');
  }, 100);
});
like image 80
Nishchit Avatar answered Oct 24 '22 11:10

Nishchit


The issue comes from the fact the the browser doesn't send any events on auto fill. It was reported as an issue on Angular's BT.

https://github.com/angular/angular.js/issues/1460

But I doubt it will be fixed from Angular since its more a browser issue.

So the solution is to do some dirty hacks like setting a timer and set the model's state to 'dirty' or trigger events from the form.

You can see some attempts here AngularJS browser autofill workaround by using a directive

like image 29
kcsoft Avatar answered Oct 24 '22 10:10

kcsoft