Home >Web Front-end >JS Tutorial >Let angularjs support browser automatic form filling_AngularJS
Recently, many front-end students have complained that the login form cannot record their own account. This is still a common problem for single-page applications and web pages that use Ajax a lot.
UserApp is a WebApp built using angularjs, but it has not been able to support the browser's "save password" feature.
Here are some of the issues found:
The form cannot be dynamically inserted into the DOM using js.
The form must actually make a POST request. (You cannot get the form content and then make a request with ajax)
When the browser automatically fills in the form, $scope cannot obtain the updated data.
Firefox is relatively simple. As long as the form element has a name attribute and the submit event is triggered, it will automatically remind the user whether to record data.
The requirements for firefox to record data are relatively simple
But there is a problem with Firefox. After automatically filling in the form, the data in $scope will not be updated. So I googled and found some hacks for this problem. But I always feel that these solutions are unnecessary, because all I need is to bring the data when submitting the form, not some very slippery two-way data binding technology. So I adopted a very simple method: get the value of the form element when submitting the form.
OK, now there is no problem with firefox, but what about chrome?
Chrome will only prompt the user whether to store the password when the form actually initiates a POST request, but in this case it cannot be operated with Ajax.
Here’s the solution:
When the form issues a Post request, use ng-submit to intercept it, return false to block it, and use ajax to submit the data.
When ajax returns successfully, the session is stored in cookies and the form is resubmitted.
When the page is reloaded, it will be found that it has been authenticated, and it will be redirected to the home page.
This will cause the page to refresh once, but it only needs to be refreshed when logging in. Just make sure that the page returns to the same address.
But if the form is dynamically added to the DOM, this method still won't work. The solution is to add a hidden form in index.html, and when you need to submit data, copy the data carried by other forms into the hidden form.
I packaged it into a directive:
scope.onSubmit(function() {
$("#login-form")[0].submit();
});
return false;
};
}
};
});
Hidden form in index.html:
Temporary login form
Controller for login:
function ajaxCallback() {
submit();
}
return false;
};
When refreshing, you will be prompted whether to resubmit the form
Now this problem is solved, but every time you press f5, the browser will remind you whether to resubmit the form. This was a bit of a pain in the ass, so I added a pre-login.html file where the hidden form would submit data and then redirect to index.html.
It’s OK now~