AngularJS, using routes without refreshes on back button

前端 未结 3 1920
名媛妹妹
名媛妹妹 2021-02-14 09:17

I\'m using angularJS to build a simple single page application using AJAX, but I\'m running into a problem when users use the native back button.

an         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-14 09:47

    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.

提交回复
热议问题