Martin
Martin

Reputation: 24318

AngularJS: Remembering a variable after a page refresh, what are my options?

Anything special available in AngularJS to remember a variable after a page refresh, i have a couple of things i need to remember i.e. Tab positions.

I was thinking about cookies here, but i have noticed jquery-ui used to do the same but they deprecated it, probably not the way to go ?

Also a cookie would be present until it was deleted or expired not just for the current session ?

Then I thought of Html 5 local storage but this got me thinking about what if the browser doesn't support html 5 local storage ? Is there anything available to say "use html 5 local storage if available" otherwise "use cookies"?

Thanks

Upvotes: 1

Views: 2927

Answers (3)

quinnirill
quinnirill

Reputation: 834

Depending on what you want to store, you have several options:

If it's UI state related, as you say, I'd go for hashbang, like Rob Di Marco suggested. The hashbang is actually even originally designed to point to a certain UI state, namely a position in the document so it fits this purpose quite well, and better yet, it leaves a history so the back button works.

If it's session related, such as a cached access token from a server, cookies are one way, yes, but using cookies is complicated at best these days given the amount of laws surrounding them. You're better off using local storage, e.g. the angular-local-storage adapter as John Tseng suggested, but I'd personally avoid using cookies as a fallback unless you want to hire a lawyer to figure out what you need to do. If it's something that doesn't prevent the application from working in any way, but just degrades the experience a bit, it's probably not worth it to go the extra mile to improve that experience. You'll have better things to improve.

Upvotes: 0

Modernizr is what you need, here there is a question similar to yours:

determine whether Web Storage is supported or not

Upvotes: 1

John Tseng
John Tseng

Reputation: 6352

There's a service that does what you're looking for: local storage with cookies as backup

https://github.com/grevory/angular-local-storage

Upvotes: 3

Related Questions