Currently I am using a service to perform an action, namely retrieve data from the server and then store the data on the server itself.
Instead of this, I want to put the data into local storage instead of storing it on the server. How do I do this?
If you use
$window.localStorage.setItem(key,value)
to store,$window.localStorage.getItem(key)
to retrieve and$window.localStorage.removeItem(key)
to remove, then you can access the values in any page.You have to pass the
$window
service to the controller. Though in JavaScript,window
object is available globally.By using
$window.localStorage.xxXX()
the user has control over thelocalStorage
value. The size of the data depends upon the browser. If you only use$localStorage
then value remains as long as you use window.location.href to navigate to other page and if you use<a href="location"></a>
to navigate to other page then your$localStorage
value is lost in the next page.Use
ngStorage
For All Your AngularJS Local Storage Needs. Please note that this is NOT a native part of the Angular JS framework.ngStorage
contains two services,$localStorage
and$sessionStorage
Check the Demo
You can use
localStorage
for the purpose.Steps:
For local storage there is a module for that look at below url:
https://github.com/grevory/angular-local-storage
and other link for HTML5 local storage and angularJs
http://www.amitavroy.com/justread/content/articles/html5-local-storage-with-angular-js/
One should use a third party script for this called called ngStorage here is a example how to use.It updates localstorage with change in scope/view.
Depending on your needs, like if you want to allow the data to eventually expire or set limitations on how many records to store, you could also look at https://github.com/jmdobry/angular-cache which allows you to define if the cache sits in memory, localStorage, or sessionStorage.