如何使用angularjs触发窗口关闭功能 [英] how to trigger a function on window close using angularjs
问题描述
我需要在用户关闭应用程序时执行一个功能,但需要考虑以下几点:
I need to execute a function when the user closes the application, but the following points need to be considered :
- 我需要执行一个
服务
的功能,然后... - ...一个超范围的纯基于javascript的功能不太可能在
有用的 - 当我使用路由时,一个范围
onLocationChangeSuccess
绑定是
无用
- I need to execute a function of one
service
, then... - ... an out-scoped pure-javascript based function is not likely to be useful here
- As I am using routes, a scoped
onLocationChangeSuccess
binding is useless as well
因此,此解决方案无法正常工作: https://stackoverflow.com/a/18355715/773595
therefore this solution is not going to work : https://stackoverflow.com/a/18355715/773595
因为这样会在每次位置改变时触发,但是我只需要
Because this will be triggered everytime the location change, but what I need is only one trigger when the tab/window is closed.
推荐答案
您可以在控制器/指令中注册一个onbeforeunload,那么您将有访问范围。在服务的情况下,我将在angular.run生命周期中注册。
You can register an onbeforeunload in your controller/directive then you'll have access to the scope. In case of a service i'd register it in the angular.run lifecycle.
angular.module('app', [])
.controller('exitController', function($scope, $window) {
$scope.onExit = function() {
return ('bye bye');
};
$window.onbeforeunload = $scope.onExit;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="exitController">
<a href="http://www.disney.com">Leave page</a>
</div>
这篇关于如何使用angularjs触发窗口关闭功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!