Skip to content

Instantly share code, notes, and snippets.

@PatrickJS
Last active December 23, 2015 23:29
Show Gist options
  • Select an option

  • Save PatrickJS/6710564 to your computer and use it in GitHub Desktop.

Select an option

Save PatrickJS/6710564 to your computer and use it in GitHub Desktop.
Confirm dialog pop up if they try and (or accidently click away from) the page
'use strict';
angular.module('angular-onbeforeunload', [])
.factory('onBeforeUnload', ['$window',
function($window) {
var leavingPageText = "You'll lose your changes if you leave";
var leavingPageText2 = "Are you sure you want to leave this page?";
function init(top, bottom) {
leavingPageText = top || leavingPageText;
leavingPageText2 = bottom || leavingPageText2;
$window.onbeforeunload = function(){
return leavingPageText;
}
return function(event, next, current) {
if(!confirm(leavingPageText + "\n\n"+leavingPageText2)) {
event.preventDefault();
}
};
}
return {
init: init
}
}
]);
angular.module('YOUR_APP', ['angular-onbeforeunload'])
.controller('MainCtrl', function(onBeforeUnload) {
// add a listener to the current scope
var onbeforeunload = $scope.$on('$locationChangeStart', onBeforeUnload.init('TOP_MESSAGE', 'BOTTOM_MESSAGE'))
$scope.submitPage = function() {
// cancel the listener for onbeforeunload
onbeforeunload();
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment