Reputation: 2741
I have an angularjs app that has a menu on top of it. When the user navigates in the menu the view gets changed with the $location command. Each view has its own controller.
I would like to keep some views "alive" after changing the view in the menu, that way when the user goes back to the previous view it is in the same state and with the same data.
How could I do it?
Thanks in advance.
Upvotes: 1
Views: 99
Reputation: 10849
Services are probably what you need.
You may hit a service which has for only purpose to store data for your controllers.
angular
.module('foo')
.service('ContextualDataService', function () {
'use strict';
var data = {},
storageIdentity = 'contextualDataService';
return {
get: function (key) {
return data[key];
},
set: function (key, value) {
data[key] = value;
},
save: function () {
localStorage.setItem(storageIdentity, JSON.stringify(data));
},
load: function () {
var items = JSON.parse(localStorage.getItem(storageIdentity));
if (items) {
for (var key in items) {
data[key] = items[key];
}
}
}
};
});
And later you can use it and isolate you controllers or anything as a namespace
angular
.module('foo')
.controller('BarController', ['ContextualDataService', function (context) {
var myData = context.get('foo.controllers.bar.savedKey') || 'myDefaultSavedKeyValue';
}]);
Upvotes: 1
Reputation: 22191
IMO, you could use the browser's local storage to store data on the page you want to keep when reloading it.
Check at this: https://github.com/grevory/angular-local-storage
Basically, in the controller of the concerned page, if data is present in local storage, you build the page rendering from them, otherwise, page with the default values will be displayed.
As soon as a change is made by the user on this page, you update the concerned set of data in the local storage.
Be aware, that you may want to clear the local storage at any time, perhaps when user has just been disconnected.
Personally, I use it to save the state of the search filters about a list of items, during the whole user navigation.
You may be interested by the introduction of local storage in HTML 5: http://diveintohtml5.info/storage.html
Upvotes: 2