在angularjs中检测页面卸载 [英] Detecting page unload in angularjs
问题描述
我有一个JavaScript对象,我需要我的angularjs应用程序的全局。当应用程序即将卸载(由于页面刷新或其他场景),我想将对象保存到浏览器存储。我相信将对象添加到$ rootScope将满足使对象成为全局对象的第一个要求,但是在 onbeforeunload
事件期间将对象写入存储器将需要访问$ rootScope变量。是否有可能在angularjs中检测到页面卸载事件?
这应该做到这一点,但我也建议避免 $ rootScope
作为全局状态是不鼓励的,你也可以在一个服务中包装 localStorage
,这样它就可以被注入并模拟测试。
$ b $ pre code $ .run([
'$ window',
'$ rootScope',$ b $函数(){
localStorage.myValue = $ rootScope.myValue;
}); $ b $($ window $ b}
]);
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?
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;
});
}
]);
这篇关于在angularjs中检测页面卸载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!