Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save singhmohancs/5f97737779a2e957b204a03b88c8195f to your computer and use it in GitHub Desktop.
Save singhmohancs/5f97737779a2e957b204a03b88c8195f to your computer and use it in GitHub Desktop.
Detect Unsaved changes and show confirm modal + angularjs
/**
* @ngdoc Directive
* @name app.confirmOnExit
*
* @description
* Prompts user while he navigating away from the current route (or, as long as this directive
* is not destroyed) if any unsaved form changes present.
*
* @element Attribute
* @scope
* @param confirmOnExit Scope function which will be called on window refresh/close or AngularS $route change to
* decide whether to display the prompt or not.
* @param confirmMessageWindow Custom message to display before browser refresh or closed.
* @param confirmMessageRoute Custom message to display before navigating to other route.
* @param confirmMessage Custom message to display when above specific message is not set.
*
* @example
* Usage:
* Example Controller: (using controllerAs syntax in this example)
*
* angular.module('app', []).controller('pageCtrl', [function () {
* this.isDirty = function () {
* // do your logic and return 'true' to display the prompt, or 'false' otherwise.
* return true;
* };
* }]);
*
* Template:
*
* <div confirm-on-exit="pageCtrl.isDirty()"
* confirm-message-window="All your changes will be lost."
* confirm-message-route="All your changes will be lost. Are you sure you want to do this?">
*
*
* @author Mohan Singh ( gmail::mslogicmaster@gmail.com, skype :: mohan.singh42 )
*/
(function () {
'use strict';
angular
.module('app')
.directive('confirmOnExit', ['$confirm', '$rootScope', function ($confirm, $rootScope) {
return {
scope: {
confirmOnExit: '&',
onSave: '&',
onDiscard: '&'
},
link: function ($scope, elem, attrs) {
var $stateChangeStartUnbind = $rootScope.$on('$stateChangeStart', function (event, next, current) {
if ($scope.confirmOnExit()) {
$confirm({
'header': 'Unsaved changes',
'body': 'There are unsaved changes. Do you want to discard or save',
'buttons': {
'accept': 'Save changes',
'cancel': 'Discard'
}
}).then(function () {
console.warn('changes accepted');
$scope.onSave();
}, function () {
$scope.onDiscard();
console.warn('changes discard');
});
}
});
$rootScope.$on('$destroy', function () {
$stateChangeStartUnbind();
});
}
};
}]);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment