Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
154 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...