Skip to content

Instantly share code, notes, and snippets.

@marco-martins
Last active March 10, 2016 11:49
Show Gist options
  • Save marco-martins/b7f96e4941f08b3e8dcc to your computer and use it in GitHub Desktop.
Save marco-martins/b7f96e4941f08b3e8dcc to your computer and use it in GitHub Desktop.
Angular directive that's fires a confirmation modal on unsaved form (if form touched)
(function () {
'use strict';
/**
* @ngdoc directive
* @name app.directive:unsavedForm
* @description
* Angular directive that's fires a confirmation modal on unsaved form (if form touched)
* @author Marco Martins
* https://gist.github.com/skarface
* # unsavedForm
*/
var message = "You have unsaved changes, are you sure you want to leave the page?";
function unsavedForm() {
return {
link: function($scope, element) {
var form = element[0];
// If element is not a form just ignore
if (form.nodeName !== 'FORM') { return; }
// Browser reload
window.onbeforeunload = function () {
if (angular.element(form).is('.ng-dirty') && angular.element(form).not('.ng-submitted')) {
return message;
}
};
// UI ROUTER before change state event
// NOTE: change '$stateChangeStart' to use with another router provider
$scope.$on('$stateChangeStart', function(event) {
if (angular.element(form).is('.ng-dirty') && !angular.element(form).is('.ng-submitted')) {
// Fires the native browser confirm modal and lock the state transition
if(!confirm(message)) {
event.preventDefault();
}
}
});
}
};
}
angular.module('app')
.directive('unsavedForm', unsavedForm);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment