When submitting a form in AngularJS and use the browser remember password functionality, and in a subsequent login attempt you let the browser fill in the login form with the username and password, the $scope
model won't be changed based on the autofill.
The only dirty hack I found is to use the following directive:
app.directive("xsInputSync", ["$timeout" , function($timeout) {
return {
restrict : "A",
require: "?ngModel",
link : function(scope, element, attrs, ngModel) {
$timeout(function() {
if (ngModel.$viewValue && ngModel.$viewValue !== element.val()) {
scope.apply(function() {
ngModel.$setViewValue(element.val());
});
}
console.log(scope);
console.log(ngModel.$name);
console.log(scope[ngModel.$name]);
}, 3000);
}
};
}]);
The problem is that the ngModel.$setViewValue(element.val());
doesn't change the model nor the view based on the element.val()
returned value. How can I accomplish that?
This is a simple fix that works for all the cases I've tested in both Firefox and Chrome. Note that with the top answer (directive w/ timeout) I had issues with -
This fix is obviously very dumb and hacky, but it works 100% of the time -
I am very new to Angularjs, but I found a simple solution to that problem=> Force Angular to reevaluate expression... by changing it! (of course you need to remember the initial value to revert to initial state) Here is the way it goes in your controller function for submitting the form:
where of course, the value entered in your password input has been set by windows and not by user.
If you are using jQuery you could do this on form submit:
HTML:
JS:
One-liner workaround in the submit handler (requires jQuery):
I force a $setValue(val()) on submit: (this works without jQuery)
You don't have to use a
$timeout
or anything like this. You can use an event system.I think it's more Angularish and does not depend on jQuery or custom event catching.
For example on your submit handler:
And then you can have an
autofill
directive like this:Finally, your HTML will be like: