I'm trying to prevent user to leave a form if he changed something in it in Angular. I've read some articles about this and found $locationChangeStart. The problem is that this method doesn't get triggered after I modify something in the form and then navigate to other page. Only the window.onbeforeunload is called.
Here is the directive:
.directive(
'confirmOnExit',
function() {
return {
link : function($scope, elem, attrs) {
$scope
.$on(
'$locationChangeStart',
function(event, next, current) {
if ($scope.addEventForm.$dirty) {
if (!confirm("The form is dirty, do you want to stay on the page?")) {
event.preventDefault();
}
}
});
window.onbeforeunload = function() {
if ($scope.addEventForm.$dirty) {
return "You have unsaved information!";
}
};
}
};
Here is the form:
<form name="addEventForm"
method="POST" ng-controller="formController" confirm-on-exit>
...
</form>
Where i am wrong?