I would like to cache some data and I read about Cache Factory, which just caches the data for the current session. But I want to keep my data in cache even after the page was reopened. What is be a better way do that?
You can use LocalStorage, sessionStorage or $cookies service :
https://docs.angularjs.org/api/ngCookies/service/$cookieStore
I think i understand what you're asking here...
If you're trying to keep the data for the current "local session" try using a service/factory, and just store the data in a local variable and create getters and setters for that.
Since the local variable isn't persisted it will be lost when the current local "session" is destroyed (i.e the user refreshes, or closes the window)
Similar to this answer: https://stackoverflow.com/a/14959540/2803660
Related
I have two html files: index.html and lobby.html. In main.js, which I load in index.html, lobby.html is loaded using window.location.href. I have tried every way of defining globals in main.js (namespaces such as: var Global = {}; Global.variableName = 0; ... Global.variableName = whatever;, simply defining variables out of function scopes: var myGlobal; and even using window. to define and use globals: window.myGlobal = 0; ... window.myGlobal = whatever;). No matter any of these approaches, every time I try to access these "globals" in a separate script in lobby.html, it always throws an undefined error. How does this make any sense?
The answer to your first question, Why can't I ...?, is that you start a new session whenever you load a page. So, any of the Javascript variables from the previous session are gone.
The other (implied) question, How can I keep the value of Javascript variables across sessions? is either to use cookies in Javascript (MDN) or append request variables to the end of your URL then process them when the new page loads: GET (SO)
When a new page is loaded, you are essentially starting a new session as explained by others here and hence the data will be reset. For retaining some data across pages, you could use HTML5 Web storage - Session storage or Local storage as per your business needs.
MDN source
The two mechanisms within Web Storage are as follows:
sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long
as the browser is open, including page reloads and restores).
localStorage does the same thing, but persists even when the browser is closed and reopened.
W3Schools
HTML local storage provides two objects for storing data on the client:
~ window.localStorage - stores data with no expiration date
~ window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)
I have localstorage for employeeid stored.When i refresh the browser get local storage value like employeeid based on employeeid get some data .when i close the browser i want to clear employeeid in local storage by using angularjs or javascript. I tried the following code.
window.onunload = close;
function close() {
//// do something...
localStorage.clear();
return null;
}
In the above code when i refresh the browser that time also window.onunload fired and clear the local storage values, but i want to clear local storage at the time of browser close only.
If you do not need this to work across different windows/tabs, then you should use sessionStorage instead of localStorage.
Where what you store into localStorage is “permanent”, sessionStorage stores values only until the window/tab is closed, similar to a “session cookie”, that is set without any lifetime – that will live only until the browser is closed (but will be available across different tabs when your site is open in more than one.)
A few more details can be found in these questions:
What is the difference between localStorage, sessionStorage, session and cookies?
HTML5 Local storage vs. Session storage
Maybe that's you're looking for Identifying Between Refresh And Close Browser Actions
I have a data-binding to $rootScope.someArray in my someData.view.html. I have written a Data service to load data and populate $rootScope.someArray and have called that service in my App's "run" method. Now If I am on the someData.view.html page and hit refresh(F5) all the data vanishes. Although if I go to home again and navigate to this html page, every thing comes back.
When I put a debug point on the place in DataService code where $rootScope.someArray is being populated, I can see data getting fetched from the backend but somehow it's lost.
Basically angular won't have the data on refresh. If you want retain you data, you need to use,
session service or local storage service based on your need (Don't forget to clear on log out).
But Putting all the data in local storage services or putting sensitive data in the local storage services is not advisable. So you need to call the Back end method and assign the data to the variable in the controller init (call using ng-init).
Note : Don't dump your array of data in RootScope. AngularJs team
itself suggesting that not to use. Instead of this use Angular
Services (not Factory) and make use this services where ever you want.
Is there a way to store temporary data on indexedDB the same way as sessionStorage:no available to other sessions (tabs) of the same domain and expire when the session is closed (affect some items on an storeObject or the whole storeObject)?
I can create a storeObject with a random name and add unload event listener to delete this storeObject when the user is exiting the page. but the problem here is that the storeObject will be deleted even if the user is just changing from a page to an other on the same domain or refreshing the page,... (same session).
I know there is some implementations of sessionStorage-like storages based on document.cookie API which is not a perfect solution for my case.
I'm not sure if there is a way to do what you want to do. I believe that indexDB is persistent until deleted. You could delete based on a timestamp, this can only happen after the user returns, or logoff button.
This may help you may be able to user localStorage if your not storing to much data:
http://www.sitepoint.com/an-overview-of-the-web-storage-api/
If you are worried about concurrent data overrides you can implement locks:
http://balpha.de/2012/03/javascript-concurrency-and-locking-the-html5-localstorage/#comments
With HTML5 and local storage, can JavaScript be used to save the state of a web page?
For example, some sites have increase font size buttons that are most likely controlled with JS. How can the property be saved so that on a refresh the size stays the same? Or is this done without JS?
Your best bet is probably to use localStorage, unless you do not want the settings to persist upon new sessions (you would use sessionStorage in that case). If you have multiple settings, you can store a serialized representation of your settings.
E.g.
var settings = {
fontSize: '11px',
otherConfig: 'test'
};
localStorage.setItem('settings', JSON.stringify(settings));
//then you can retrieve it
settings = JSON.parse(localStorage.getItem('settings'));
console.log(settings.fontSize); //11px
Note that if you want the settings to persist when users connects from multiple computers, you will have to use some server-side support.
Yes, it is done with Javascript. You can use
Cookies
Sessionstorage
This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.
Localstorage
localStorage is the same as sessionStorage with same same-origin rules applied but it is persistent.
The better/easier ones are sessionStorage and localStorage. The problem is that they aren't supported by old browsers.
Instead, dealing with cookies can be a nightmare, but they work on old browsers too.
Yes can save state to localStorage.
assume you have an object :
var settingsObj={
pageClass:'bigFont',
widgetSortOrder : [1,5,3,7]
}
You could save that whole object to one local storage key by stringifying the object. When page loads you would see if that key exists in localStorage and have your javascript do whatever it neds to with those settings
To stringify and store:
localStorage.setItem('mySettings', JSON.stringify(settingsObj) );
To retrieve from storage and convert to js object
var settings=JSON.parse(localStorage.getItem('mySettings'));