如何使用angularjs触发窗口关闭功能 [英] how to trigger a function on window close using angularjs

查看:752
本文介绍了如何使用angularjs触发窗口关闭功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要当用户关闭应用程序来执行的功能,但以下几点需要考虑:


  • 我需要执行一个服务的功能,然后...

  • ...一个彻头彻尾范围的纯基于JavaScript的功能是不是可能是
    这里有用

  • 当我使用的路线,一个作用域 onLocationChangeSuccess 绑定
    没用以及

因此​​该方案是行不通的: http://stackoverflow.com/a/18355715/773595

由于这将是触发每次的位置的变化,但我需要的是只有一个当标签/窗口关闭触发。


解决方案

您可以注册在你的控制器/指令的onbeforeunload那么你就必须访问范围。在服务的情况下,我会注册它在angular.run生命周期。

\r
\r

angular.module(应用,[])\r
  .controller('exitController',函数($范围,$窗口){\r
    $ scope.onExit =功能(){\r
      返回('再见');\r
    };\r
\r
   $ window.onbeforeunload = $ scope.onExit;\r
  });

\r

&LT;脚本SRC =htt​​ps://ajax.googleapis.com/ajax /libs/jquery/2.1.1/jquery.min.js\"></script>\r
&所述; SCRIPT SRC =htt​​ps://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js&GT;&下; /脚本&GT;\r
&LT; D​​IV NG-应用=应用程序NG控制器=exitController&GT;\r
  &LT; A HREF =htt​​p://www.disney.com&GT;离开网页&LT; / A&GT;\r
&LT; / DIV&GT;

\r

\r
\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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆