Angular: Restore scope from sessionStorage

user1973285 picture user1973285 · Aug 21, 2014 · Viewed 8k times · Source

I am trying to retrieve my search and filter data from sessionStorage when the page refreshes.

sessionStorage.restorestate returns undefined, does anyone know why?

app.run(function($rootScope) {
    $rootScope.$on("$routeChangeStart", function(event, next, current) {
      if (sessionStorage.restorestate == "true") {
        $rootScope.$broadcast('restorestate'); //let everything know we need to restore state
        sessionStorage.restorestate = false;
      }
    });

    //let everthing know that we need to save state now.
    window.onbeforeunload = function(event) {
      $rootScope.$broadcast('savestate');
    };
  });

Plunkr: http://plnkr.co/edit/oX4zygwB0bDpIcmGFgYr?p=preview

Answer

Hugo Wood picture Hugo Wood · Aug 21, 2014

When you refresh the page in an Angular app, it is like completely rebooting the application. So to restore from the session storage, just do it when the service factory executes.

app.factory('CustomerSearchService', ['$rootScope',
    function($rootScope) {
        ...
        function restoreState() {
            service.state = angular.fromJson(sessionStorage.CustomerSearchService);
        }
        if (sessionStorage.CustomerSearchService) restoreState();
        ...
    }
]);

The saving part was already correct.

app.factory('CustomerSearchService', ['$rootScope',
    function($rootScope) {
        ...
        function saveState() {
            sessionStorage.CustomerSearchService = angular.toJson(service.state);
        }
        $rootScope.$on("savestate", saveState);
        ...
    }
]);

app.run(function($rootScope) {
    window.onbeforeunload = function(event) {
      $rootScope.$broadcast('savestate');
    };
});

DEMO