What is the difference between ngStorage and $window.localStorage? When is it better to use one instead that the other? I have to choose one of them for a web app. I have to save data of profile user and the token
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
The variable
$window
usually is the globalwindow
variable. The reason that Angular recommends using$window
is because sometimes you would like to mock or replace the "real"window
object (for testing purposes, for example).Said this, using
$window.localStorage
means that you are using the Local Storage's vanilla API, while ngStorage isSource here
It works!
This is normal html5 local storage:
It gives you to objects to access the storage - window.localStorage and window.sessionStorage
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session, so data is lost when the browser tab is closed
To retrieve data you would do something like this
So if you wanted to do this in angular you would use the $window service but it would behave the same as the examples above.
Source
To address ngStorage:
You can pass $localStorage or $sessionStorage by reference under $scope:
Then you can use $storage as and other angular variable
Source
If you will be working with angularjs in your webapp I would use ngStorage because you will be more comfortable and familiar with the syntax. That is just my opinion though.
Just be mindful ngStorage internally uses an Angular watch to monitor changes to the
$storage
/$localStorage
objects i.e a digest cycle is required to persist your new values reliably into the browser's local storage. Normally not a problem but if you store a value in$localStorage
and open a new tab without a digest cycle occurring, you might not be able to see the stored values in your newly opened tab/window.Ran into this problem on IE and had to use
window.localStorage
to get around it.