Page load detection in angularjs

I have a javascript object that I need globally for my angularjs application. When the application is unloaded (due to a page refresh or some other script), I would like to save the object to the browser storage. I believe that adding an object to $ rootScope would fulfill the first requirement to make the object global, but writing the object to the repository during the onbeforeunload event onbeforeunload require access to the $ rootScope variable. Can a page load event be detected in angularjs?

+7
angularjs global-variables rootscope onbeforeunload
source share
1 answer

That should do it, but I also suggest avoiding $rootScope , as global state is not recommended, and you can also wrap localStorage in a service so that it can be injected and mocked with testing.

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

All Articles