Skip to content

Instantly share code, notes, and snippets.

@singhmohancs
Last active June 2, 2016 09:03
Show Gist options
  • Save singhmohancs/d75fcde0826c0ab2e471fa74e08485ba to your computer and use it in GitHub Desktop.
Save singhmohancs/d75fcde0826c0ab2e471fa74e08485ba to your computer and use it in GitHub Desktop.
Warn on route change if unsaved changes
<form name="anything" confirm-on-exit>......</form>
<form name="anything" confirm-on-exit="collection">......</form>
(function () {
'use strict';
angular.module("app").directive('confirmOnExit', function () {
return {
link: function ($scope, elem, attrs) {
if (elem[0].nodeName === 'FORM') { //the user wants to check a form
window.onbeforeunload = function () {
if (angular.element(elem[0]).hasClass('ng-dirty') && !angular.element(elem[0]).hasClass('ng-submitted')) {
return "You have unsaved changes - are you sure you want to leave the page?";
}
}
$scope.$on('$locationChangeStart', function (event, next, current) {
if (angular.element(elem[0]).hasClass('ng-dirty') && !angular.element(elem[0]).hasClass('ng-submitted')) {
if (!confirm("You have unsaved changes - are you sure you want to leave the page?")) {
event.preventDefault();
}
}
});
}
else { //the user wants to check a specific collection
if (attrs.confirmOnExit) {
var loaded = false;
var hasUnsavedChanges = false;
$scope.$watchCollection(
attrs.confirmOnExit,
function (newValue, oldValue) {
if (!loaded && newValue !== undefined) { // the collection will change once on initialization; allow for this
loaded = true;
}
else if (newValue !== undefined) { // the collection has already been initialized; mark it as changed
hasUnsavedChanges = true;
}
}
);
$scope.$on('$locationChangeStart', function (event, next, current) {
if (hasUnsavedChanges) {
if (!confirm("Make sure you save your changes before you go!")) {
event.preventDefault();
}
}
});
}
else {
console.log('Please pass in a collection for confirm-on-exit to work correctly.');
console.log('Example: <div confirm-on-exit="collectionName">...</div>');
}
}
}
};
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment