-
Notifications
You must be signed in to change notification settings - Fork 0
/
ng-prevent-navigation.js
67 lines (60 loc) · 2.34 KB
/
ng-prevent-navigation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
angular.module('preventNavigation', [])
.service( '$preventNavigation', function($rootScope, $location) {
var unbind_cb, obu;
function clear() {
if (unbind_cb) {
unbind_cb();
unbind_cb = null;
window.onbeforeunload = obu;
obu = null;
}
}
return {
permit: function(check_cb, text) {
if(!text) text = "Page has unsaved data";
clear();
if(check_cb && check_cb instanceof Function) {
obu = window.onbeforeunload;
window.onbeforeunload = onbeforeunload;
unbind_cb = $rootScope.$on('$locationChangeStart', function(event, to_url) {
event.preventDefault();
check_cb(function allow_navigation() {
clear();
setTimeout(function() {
$location.url(to_url.replace(location.origin, ''));
$rootScope.$$phase || $rootScope.$apply();
}, 0);
});
});
} else if(!check_cb) {
obu = window.onbeforeunload;
window.onbeforeunload = onbeforeunload;
unbind_cb = $rootScope.$on('$locationChangeStart', function(event, to_url) { event.preventDefault()});
}
function onbeforeunload() {
try {
obu && obu()
}
catch(e) {
console.error(e)
}
check_cb instanceof Function && check_cb(function(){});
return text;
}
}
}
})
.directive('ngPreventNavigation', function($preventNavigation) {
return {
restrict: "A",
link: function (scope, element, attr) {
scope.$watch(attr.ngPreventNavigation, function(result) {
$preventNavigation.permit(!result, attr.ngPreventNavigationText);
});
scope.$on('$destroy', function() {
$preventNavigation.permit(true);
})
}
}
})
;