Javascript onBeforeUnload应用于整个应用程序
我使用的服务基本上是在用户尝试刷新或关闭页面时弹出一个框,它工作正常,但基本上我只想应用于特定页面,但问题是应用于其余页面 我尝试在包含特定状态位置的if语句内部应用,但仍在应用程序的其余部分中应用 服务:Javascript onBeforeUnload应用于整个应用程序,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我使用的服务基本上是在用户尝试刷新或关闭页面时弹出一个框,它工作正常,但基本上我只想应用于特定页面,但问题是应用于其余页面 我尝试在包含特定状态位置的if语句内部应用,但仍在应用程序的其余部分中应用 服务: angular.module('farm') .factory('beforeUnload', function ($rootScope, $window) { // Events are broadcast outside the Scope Lifecycle
angular.module('farm')
.factory('beforeUnload', function ($rootScope, $window) {
// Events are broadcast outside the Scope Lifecycle
$window.onbeforeunload = function (e) {
var confirmation = {};
var event = $rootScope.$broadcast('onBeforeUnload', confirmation);
if (event.defaultPrevented) {
return confirmation.message;
}
};
$window.onunload = function () {
$rootScope.$broadcast('onUnload');
};
return {};
})
.run(function (beforeUnload) {
// Must invoke the service at least once
});
控制器:
if ($state.includes("app.cal.lab.result")){
$scope.$on('onBeforeUnload', function (e, confirmation) {
confirmation.message = "All data willl be lost.";
e.preventDefault();
});
$scope.$on('onUnload', function (e) {
console.log('leaving page'); // Use 'Preserve Log' option in Console
});
}
如果使用ui路由器,只需使用
$location
或$state
检查当前路径即可。不需要角度事件只要用$location
或$state
检查当前路径(如果使用ui路由器)。不需要角度事件