Detect unsaved changes and alert user when he tries to leave the page without saving these changes
-
include the script tag of this module
<script src="unsavedChanges.js"></script>
-
Register the
unsavedChanges
module in your applicationangular.module('app', ['unsavedChanges']);
-
Attach a listener and pass the two arguments: current
$scope
and object which changes the service should listenunsavedChanges.fnListen($scope, $scope.myObject);
-
To reattach listener, for example after saving the changes by user, use the same method.
$scope.myResource.$update(function(){ unsavedChanges.fnListen($scope, $scope.myResource); })
-
To remove all listeners, just call the
unsavedChanges.fnRemoveListener()
method. It's useful when you want to redirect user after deleting the object, for example.$scope.myResource.$delete(function(){ unsavedChanges.fnRemoveListener(); })