简体   繁体   中英

Persisting data across page refresh in Angular

angular.module('eventTracker', [])

.controller('MainCtrl', ['$scope', 'Event', function($scope, Event){
    $scope.eventData = {}
    $scope.onSubmit = function(){
        Event.Add($scope.eventData)
        $scope.eventData = {}
    }
}])

.factory('Event', function(){
    if (!eventList) {
        var eventList = []
    }
    return {
        Add: function(event){
            eventList.push(event)
        },
        List: eventList
    }
})

Hi all, I am trying to persist eventList through a page refresh, and I'd love some feedback as to why that might be happening! I'd rather not use cookies, localstorage, or rootscope. I thought my service was set up correctly, but I guess not. Any help would be greatly appreciated! Everything works perfectly except when I refresh the page, I lose all previous data.

When you refresh the page in a browser, all stored data within Javascript variables are lost. If you need to refresh the page, the data needs to be stored in a database and you need to request that data on page load using something like AJAX.

If you are looking to change 'pages' within your AngularJS app you should use routing and multiple views to simulate multiple web pages. This will enable you to pull up different pages while maintaining any data that is stored within your service.

Check out routing inside of the AngularJS tutorial.

Your options for cross page state really boil down to:

Server side - ie persist/retrieve from the server via ajax

Client side:

  • Cookies
  • Other state stores such as flash (obsolete), HTML 5 local storage, session storage
  • Wrap the above in 3rd party library such as http://amplifyjs.com/api/store/

If it's very small amounts of state and the above options aren't suitable you could encode the state in URLs (eg as a query string parameter when you change page) but that's a lot of work for more than the most trivial scenario.

Everything within the angular app/scope/rootscope will be lost on a page refresh.

This can be looked on as a "good thing" as it gives you a chance to clear out the browser memory. SPA applications are great, but enourmous SPA applications carry a lot of bloat and risks of a single bad script bringing the entire application down. Breaking a SPA up into several mini applications has a lot of benefits going for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM