ngStorage
An AngularJS module that makes Web Storage working in the Angular Way. Contains two services: $localStorage
and $sessionStorage
.
Differences with Other Implementations
-
No Getter 'n' Setter Bullshit - Right from AngularJS homepage: "Unlike other frameworks, there is no need to [...] wrap the model in accessors methods. Just plain old JavaScript here." Now you can enjoy the same benefit while achieving data persistence with Web Storage.
-
sessionStorage - We got this often-overlooked buddy covered.
-
Cleanly-Authored Code - Written in the Angular Way, well-structured with testability in mind.
-
No Cookie Fallback - With Web Storage being readily available in all the browsers AngularJS officially supports, such fallback is largely redundant.
Install
bower install ngstorage
Usage
Require ngStorage and Inject the Services
angular;
Demo
Read and Write |Pass $localStorage
(or $sessionStorage
) by reference to a hook under $scope
in plain ol' JavaScript:
$scope$storage = $localStorage;
And use it like you-already-know:
{{$storage.counter}}
Optionally, specify default values using the
$default()
method:$scope$storage = $localStorage;
With this setup, changes will be automatically sync'd between $scope.$storage
, $localStorage
, and localStorage - even across different browser tabs!
Demo
Read and Write Alternative (Not Recommended) |If you're not fond of the presence of $scope.$storage
, you can always use watchers:
$scopecounter = $localStoragecounter || 42; $scope; $scope;
This, however, is not the way ngStorage is designed to be used with. As can be easily seen by comparing the demos, this approach is way more verbose, and may have potential performance implications as the values being watched quickly grow.
Demo
Delete |Plain ol' JavaScript again, what else could you better expect?
// Both will dodelete $scope$storagecounter;delete $localStoragecounter;
This will delete the corresponding entry inside the Web Storage.
Demo
Delete Everything |If you wish to clear the Storage in one go, use the $reset()
method:
$localStorage;
Optionally, pass in an object you'd like the Storage to reset to:
$localStorage;
Demo
Permitted Values |You can store anything except those not supported by JSON:
Infinity
,NaN
- Will be replaced withnull
.undefined
, Function - Will be removed.
Minification
Just run $ npm install
to install dependencies. Then run $ grunt
for minification.
Todos
- ngdoc Documentation
- Namespace Support
- Unit Tests
- Grunt Tasks
Any contribution will be appreciated.