Angular & unload (with issue)
by Julien Roche
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.js"></script>
<body>
<h1>Unload event management</h1>
<my-directive></my-directive>
</body>
CSS
my-directive {
background-color: yellow;
border: 1px solid black;
color: black;
display: inline-block;
height: 35px;
line-height: 35px;
text-align: center;
width: 300px;
}
JavaScript
window.onbeforeunload = function(event) {
console.log('Before unload global');
return 'Date will be lost: are you sure?';
}
angular
.module('myApp', [])
.directive('myDirective', function () {
return {
'restrict': 'E',
'template': '<button ng-click="vm.reload()">Reload page</button>',
'scope': { },
'controller': function () {
this.reload = function () {
location.reload();
};
},
'controllerAs': 'vm',
'bindToController': true,
'link': function ($scope) {
function beforeUnloadListener() {
window.removeEventListener('beforeunload', beforeUnloadListener, false);
console.log('Before unload from directive');
}
window.addEventListener('beforeunload', beforeUnloadListener, false);
$scope.$on('$destroy', function () {
window.removeEventListener('beforeunload', beforeUnloadListener, false);
});
}
};
});
angular.bootstrap(document.body, ['myApp']);