如何使用angularjs在窗口关闭时触发函数 [英] how to trigger a function on window close using angularjs

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

问题描述

我需要在用户关闭应用程序时执行一个函数,但需要考虑以下几点:

  • 我需要执行一个service的函数,然后...
  • ... 一个超出范围的基于纯 javascript 的函数不太可能是在这里很有用
  • 当我使用路由时,范围内的 onLocationChangeSuccess 绑定是也没有用

因此此解决方案不起作用:https://stackoverflow.com/a/18355715/773595

因为每次位置改变都会触发这个,但我需要的只是在选项卡/窗口关闭时触发一个.

解决方案

你可以在你的控制器/指令中注册一个 onbeforeunload 然后你就可以访问范围.如果是服务,我会在 angular.run 生命周期中注册它.

angular.module('app', []).controller('exitController', function($scope, $window) {$scope.onExit = 函数(){返回('再见');};$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">离开页面</a>

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 : 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.

解决方案

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天全站免登陆