If user tries to leave unsaved edited form, a message box pop-up
"This page is asking you to confirm that you want to leave - data you have entered may not be saved. Leave Page and Stay on Page"
Can we invoke this confirmation box through some special function of browser? I want to implement it in AngularJS application
I think you would need to use
$window.alert
or$window.confirm
or beforeroutechangeAngular documentation
You can easily protect your form with jQuery with this simple unobtrusive code. Put in just before your
</body>
closing tag.If you want to cancel the route change when you determine your form is dirty, you can do this:
This will cancel the routing and keep you on the current page.
Warlock's answer is partly right, but in doing so, you'd break testability.
In Angular, you'd want to use $window, and you'll want to watch
$dirty
on your form. You'll need to have a named form, noticename="myForm"
below. Then you can$watch
$dirty
on the form in your$scope
:HTML
Here's a plunk to demonstrate: http://plnkr.co/edit/3NHpU1
You could use the "onbeforeunload" event. The syntax is as follows:
This event will popup that confirmation dialog that you described above asking whether or not the user truly wants to leave the page.
Hope this helps.
I liked @blesh's answer, but I think it fails to account for internal url changes (for example, if you use ngView on your application and visit different internal views). window.onbeforeunload never gets called when the hash # changes. In this case, you have to listen to both window.onbeforeunload and $locationChangeStart:
See plunkr here: http://plnkr.co/edit/R0Riek?p=preview