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

查看:2497
本文介绍了如何使用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屋!

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