9

当页面刷新时,我正在尝试从 sessionStorage 中检索我的搜索和过滤数据。

sessionStorage.restorestate 返回未定义,有谁知道为什么?

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

4

1 回答 1

13

当您在 Angular 应用程序中刷新页面时,就像完全重新启动应用程序一样。因此,要从会话存储中恢复,只需在服务工厂执行时执行。

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

保存部分已经正确。

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');
    };
});

演示

于 2014-08-21T15:57:37.377 回答