Created
March 7, 2017 18:28
-
-
Save jonocairns/175b4d8a3b10cc702eb9fe8aa51994a8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Controls the actions of the confirm on exit component | |
* | |
* @export | |
* @class ConfirmOnExitController | |
*/ | |
export class ConfirmOnExitController { | |
public confirmOnExit: Function; | |
public confirmMessageRoute: string; | |
public confirmMessage: string; | |
/* @ngInject */ | |
constructor(private $transitions: any) { | |
} | |
/** | |
* Initialiser for the confirm on exit component. This will add hooks to the window.onbeforeunload and $transition to ensure | |
* a user is prompted if they have unsaved changes on the page. | |
* | |
* @returns {void} | |
* | |
* @memberOf ConfirmOnExitController | |
*/ | |
public $onInit(): void { | |
if(!this.confirmOnExit || !this.confirmMessageRoute || !this.confirmMessage) { | |
console.log('Not all required parameters supplied for on exit directive'); | |
return; | |
} | |
// this stops the user from navigating outside of the current portal or closing the window | |
window.onbeforeunload = () => { | |
if (this.confirmOnExit()) { | |
return this.confirmMessage; | |
} | |
}; | |
// stops the user from navigating to other parts of the application with unsaved changes | |
this.$transitions.onStart({from: this.confirmMessageRoute, to: '*'}, (transition: any) => { | |
if (this.confirmOnExit()) { | |
if (!confirm(this.confirmMessage)) { | |
return false; | |
} | |
} | |
}); | |
} | |
/** | |
* Unbinds the onbeforeunload event handler from the window | |
* | |
* | |
* @memberOf ConfirmOnExitController | |
*/ | |
public $onDestroy() { | |
window.onbeforeunload = null; | |
} | |
} | |
/** | |
* Component options for the confirm on exit component | |
* @type {ng.IComponentOptions} | |
*/ | |
export const ConfirmOnExitComponent: ng.IComponentOptions = { | |
controller: ConfirmOnExitController, | |
controllerAs: 'ctrl', | |
bindings: { | |
confirmOnExit: '&', | |
confirmMessageRoute: '@', | |
confirmMessage: '@' | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment