Difference between ngStorage and $window.localStorage

panagulis72 picture panagulis72 · Apr 14, 2016 · Viewed 8k times · Source

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

Answer

sebenalern picture sebenalern · Apr 14, 2016

This is normal html5 local storage:

With local storage, web applications can store data locally within the user's browser. Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server. Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

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

localStorage.getItem("lastname"); 

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:

An AngularJS module that makes Web Storage working in the Angular Way. Contains two services: $localStorage and $sessionStorage. No dealing with getters and setters like you have to in $window service

You can pass $localStorage or $sessionStorage by reference under $scope:

$scope.$storage = $localStorage;

Then you can use $storage as and other angular variable

<body ng-controller="Ctrl">
    <button ng-click="$storage.counter = $storage.counter + 1">{{$storage.counter}}</button>
</body>

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.