Skip to content

Instantly share code, notes, and snippets.

@heneryville
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heneryville/e8d815a3a35c83f4fb8a to your computer and use it in GitHub Desktop.
Save heneryville/e8d815a3a35c83f4fb8a to your computer and use it in GitHub Desktop.
Save stuff on angular onbeforeunload
angular.module('myapp')
.controller('MyController',['$rootScope',function($rootScope){
$rootScope.$on('beforeunload',function(){
//Save junk
});
}).factory('onunload',['$rootScope',function($rootScope){
window.onbeforeunload = function(e){ //Listen for events on the window
$rootScope.$apply(function(){ //If we didn't do this through $apply, there woudl be no digest cycle and changes to the DOM would show up late
$rootScope.$broadcast('beforeunload'); //Angular does pubsub via the $broadcast function available on scopes. $emit is similar
});
}
}).run(['onunload',function(onunload){}]) //The onunload service needs to be required into something to be run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment