AngularJS, using routes without refreshes on back button

与世无争的帅哥 提交于 2019-12-03 11:55:16
biofractal

Yep, the Back button and the the Refresh button are a real pain. You have two choices:

  1. You keep things simple and just allow your state to be fetched for each location change. This treats a user triggered back button click or a refresh as any normal location change. Data re-fetching can be mitigated by http caching.

  2. You maintain your own state on the client and restore it when required, possibly using SessionStorage to keep things clean.

I chose the latter option and it all works just fine for me. See these self answered questions for detailed code examples.

Use a service to keep a singleton state, which exposes functions to get/reload/etc. Here is a very simple example, just to get you started:

.factory('FeedService', ['$http', function($http){
    var state = {};

    var loadFeed = function(){
        $http.get('http://api.example.com').then(function(result){
            state.feed = result.items;                
        });
    };

    // load the feed on initialisation
    loadFeed();

    return {
        getState: function(){
            return state;
        }
    };
}])

.controller('MenuCtrl', ['$scope', 'FeedService', function($scope, FeedService) {        
    // assign the feed container to any scope that you want to use for view
    $scope.cont = FeedService.getState();
})

Again, this is very basic, and is simply showing you how you can use a service to store a persistent state between routes.

if your parameter 'id' in the route contains any character that is being decoded during the http request (like ' ' => '%20') then your route will not work. try to perform encodeURIComponent() on your string before using it for the routing.

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