Detecting page unload in angularjs

别来无恙 提交于 2019-12-10 12:58:44

问题


I have a javascript object which I need global to my angularjs application. When the application is about to be unloaded (due to a page refresh or some other scenario), I would like to persist the object to browser storage. I believe adding the object to $rootScope would fulfill the first requirement of making the object global, but writing the object to storage during the onbeforeunload event, would require access to the $rootScope variable. Is it possible to detect a page unload event in angularjs?


回答1:


This should do it, but I also suggest avoiding $rootScope as global state is discouraged, and you might also wrap localStorage in a service so that it can be injected and mocked for testing.

.run([
  '$window',
  '$rootScope',
  function($window, $rootScope) {
    $window.addEventListener('beforeunload', function() {
      localStorage.myValue = $rootScope.myValue;
    });
  }
]);


来源:https://stackoverflow.com/questions/27367728/detecting-page-unload-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!