如何使用angularjs触发窗口关闭功能 [英] how to trigger a function on window close using angularjs
问题描述
我需要当用户关闭应用程序来执行的功能,但以下几点需要考虑:
- 我需要执行一个
服务的功能
,然后... - ...一个彻头彻尾范围的纯基于JavaScript的功能是不是可能是
这里有用 - 当我使用的路线,一个作用域
onLocationChangeSuccess
绑定
没用以及
因此该方案是行不通的: http://stackoverflow.com/a/18355715/773595
由于这将是触发每次的位置的变化,但我需要的是只有一个当标签/窗口关闭触发。
您可以注册在你的控制器/指令的onbeforeunload那么你就必须访问范围。在服务的情况下,我会注册它在angular.run生命周期。
angular.module(应用,[])\r
.controller('exitController',函数($范围,$窗口){\r
$ scope.onExit =功能(){\r
返回('再见');\r
};\r
\r
$ window.onbeforeunload = $ scope.onExit;\r
});
\r
&LT;脚本SRC =https://ajax.googleapis.com/ajax /libs/jquery/2.1.1/jquery.min.js\"></script>\r
&所述; SCRIPT SRC =https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js&GT;&下; /脚本&GT;\r
&LT; DIV NG-应用=应用程序NG控制器=exitController&GT;\r
&LT; A HREF =http://www.disney.com&GT;离开网页&LT; / A&GT;\r
&LT; / DIV&GT;
\r
I need to execute a function when the user closes the application, but the following points need to be considered :
- 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
therefore this solution is not going to work : http://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.
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屋!