localStorage and sessionStorage done right for AngularJS.

Related tags

Storage ngStorage
Overview

ngStorage

Build Status Dependency Status devDependency Status

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

bower install ngstorage

NOTE: We are ngstorage and NOT ngStorage. The casing is important!

NPM

npm install ngstorage

NOTE: We are ngstorage and NOT ngStorage. The casing is important!

nuget

Install-Package gsklee.ngStorage

Or search for Angular ngStorage in the nuget package manager. https://www.nuget.org/packages/gsklee.ngStorage

CDN

cdnjs

cdnjs now hosts ngStorage at https://cdnjs.com/libraries/ngStorage

To use it

<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.10/ngStorage.min.js"></script>

jsDelivr

jsDelivr hosts ngStorage at http://www.jsdelivr.com/#!ngstorage

To use is

<script src="https://cdn.jsdelivr.net/npm/[email protected]/ngStorage.min.js"></script>

Usage

Require ngStorage and Inject the Services

angular.module('app', [
    'ngStorage'
]).controller('Ctrl', function(
    $scope,
    $localStorage,
    $sessionStorage
){});

Read and Write | Demo

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:

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

Optionally, specify default values using the $default() method:

$scope.$storage = $localStorage.$default({
    counter: 42
});

With this setup, changes will be automatically sync'd between $scope.$storage, $localStorage, and localStorage - even across different browser tabs!

Read and Write Alternative (Not Recommended) | Demo

If you're not fond of the presence of $scope.$storage, you can always use watchers:

$scope.counter = $localStorage.counter || 42;

$scope.$watch('counter', function() {
    $localStorage.counter = $scope.counter;
});

$scope.$watch(function() {
    return angular.toJson($localStorage);
}, function() {
    $scope.counter = $localStorage.counter;
});

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.

Delete | Demo

Plain ol' JavaScript again, what else could you better expect?

// Both will do
delete $scope.$storage.counter;
delete $localStorage.counter;

This will delete the corresponding entry inside the Web Storage.

Delete Everything | Demo

If you wish to clear the Storage in one go, use the $reset() method:

$localStorage.$reset();

Optionally, pass in an object you'd like the Storage to reset to:

$localStorage.$reset({
    counter: 42
});

Permitted Values | Demo

You can store anything except those not supported by JSON:

  • Infinity, NaN - Will be replaced with null.
  • undefined, Function - Will be removed.

Usage from config phase

To read and set values during the Angular config phase use the .get/.set functions provided by the provider.

var app = angular.module('app', ['ngStorage'])
.config(['$localStorageProvider',
    function ($localStorageProvider) {
        $localStorageProvider.get('MyKey');

        $localStorageProvider.set('MyKey', { k: 'value' });
    }]);

Prefix

To change the prefix used by ngStorage use the provider function setKeyPrefix during the config phase.

var app = angular.module('app', ['ngStorage'])
.config(['$localStorageProvider',
    function ($localStorageProvider) {
        $localStorageProvider.setKeyPrefix('NewPrefix');
    }])

Custom serialization

To change how ngStorage serializes and deserializes values (uses JSON by default) you can use your own functions.

angular.module('app', ['ngStorage'])
.config(['$localStorageProvider', 
  function ($localStorageProvider) {
    var mySerializer = function (value) {
      // Do what you want with the value.
      return value;
    };
    
    var myDeserializer = function (value) {
      return value;
    };

    $localStorageProvider.setSerializer(mySerializer);
    $localStorageProvider.setDeserializer(myDeserializer);
  }];)

Minification

Just run $ npm install to install dependencies. Then run $ grunt for minification.

Hints

Watch the watch

ngStorage internally uses an Angular watch to monitor changes to the $storage/$localStorage objects. That means that a digest cycle is required to persist your new values into the browser local storage. Normally this is not a problem, but, for example, if you launch a new window after saving a value...

$scope.$storage.school = theSchool;
$log.debug("launching " + url);
var myWindow = $window.open("", "_self");
myWindow.document.write(response.data);

the new values will not reliably be saved into the browser local storage. Allow a digest cycle to occur by using a zero-value $timeout as:

$scope.$storage.school = theSchool;
$log.debug("launching and saving the new value" + url);
$timeout(function(){
   var myWindow = $window.open("", "_self");
   myWindow.document.write(response.data);
});

or better using $scope.$evalAsync as:

$scope.$storage.school = theSchool;
$log.debug("launching and saving the new value" + url);
$scope.$evalAsync(function(){
   var myWindow = $window.open("", "_self");
   myWindow.document.write(response.data);
});

And your new values will be persisted correctly.

Todos

  • ngdoc Documentation
  • Namespace Support
  • Unit Tests
  • Grunt Tasks

Any contribution will be appreciated.

Comments
  • How to wait on delete to take place

    How to wait on delete to take place

    In my app, when a user logs out I want to

    1. Delete their auth token from $localStorage.
    2. Reload the page

    I noticed that this code wasn't working:

    delete $localStorage.authToken;
    $window.location.href = '/';
    

    When the page reloads, the auth token is still present.

    So, as an experiment I put the reload in a timeout and it worked.

    delete $localStorage.authToken;
    $timeout(function () {
        $window.location.href = '/';
    }, 110);
    

    I also noticed that the timeout had to be greater than 100... which leads me to believe that this has something to do with _debounce section in your code, which I don't quite understand, yet.

    What's the best way that I can be sure that the data has been removed from web storage before reloading the page?

    opened by ronnieoverby 24
  • Add prefix configuration via ngStorageProvider

    Add prefix configuration via ngStorageProvider

    Now one can set his own prefix for storage keys via ngStorageProvider

    closes https://github.com/gsklee/ngStorage/issues/26 and https://github.com/gsklee/ngStorage/issues/17

    opened by chicoxyzzy 21
  • Looking for Maintainers

    Looking for Maintainers

    Hi everyone, sorry for the dead silence for quite a long time.

    To put it short, I've moved away from the Angular ecosphere and am not very likely to invest any more substantial amount of time into this project, so I've decided to open it up for those who actively use it in their daily developments.

    I've got no prior experience on this so I'm not sure if turning this repo into an organization is good or bad, so please weigh in and share your thoughts on the pros and cons of establishing an organization to oversee this project.

    Also if you're interested in helping to maintain and shape the future of ngStorage, you're more than welcome to give a shout below and let us know how you'd like to help.

    cc @egilkh @raynode @sompylasar @AyogoHealth @scalablepress @halkon and thanks for your past contributions!

    opened by gsklee 16
  • ngStorage error using karma.conf

    ngStorage error using karma.conf

    My karma cannot use my ngstorage: Uncaught Error: Mismatched anonymous define() module: function (angular) {

    karma.conf files: [ 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-resource/angular-resource.js', 'bower_components/ngstorage/ngStorage.js', 'test-main.js', {pattern: 'lib//*.js', included: false}, {pattern: 'src//.js', included: false}, {pattern: 'test/__/.js', included: false} ],

    opened by jbarros35 15
  • Access from a provider or config block not possible with current implementation choices.

    Access from a provider or config block not possible with current implementation choices.

    Hi,

    Could it be possible to register $sessionStorage and $localStorage using providers instead of factory to allow usage of storage in application providers / configuration blocks.

    I know that the usage of $rootScope you do in your implementation will cause problem in this approach, but maybe you could just implement good old plain get() and set() methods to access the local/session storage from providers without providing the angular binding magic ?

    My use case is simple (and I think, one of the most commun use case for local/session storage ) : a configuration block who must read in the sessionStorage to inject a custom security header using $httpProvider.

    opened by pgayvallet 15
  • Possible bug?

    Possible bug?

    Hi,

    When I store a key I see that it store like this "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjEsImlhdCI6MTQzOTk4ODI3MX0.qkh74V2BJYozwnD8y__louOMJ0IcTqtSAvR19eQ3s9s"

    So if you print it in console with localStorage.mykey the result is ""eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjEsImlhdCI6MTQzOTk4ODI3MX0.qkh74V2BJYozwnD8y__louOMJ0IcTqtSAvR19eQ3s9s""

    I don't want the extra apices on the string, I think it's bug because if you store with normal storage (localStorage.test = "test") and you print it you got "test" and not ""test""

    opened by furyscript 11
  • Is it compatible with angular 1.4/material?

    Is it compatible with angular 1.4/material?

    Is it compatible with angular 1.4/material? if yes, can you give some examples how to use without $scope? because $scope is not available in components coontroller

    opened by talgatbaltasov 11
  • $reset does not remove items from webStorage

    $reset does not remove items from webStorage

    I just recently tried this ngmodule and found that when I reset the storage when I try to access the $sessionStorage it reloads the data, because it is still there... I patched it locally to make it work in this way:

    $reset: function(items) { for (var k in $storage) { '$' === k[0] || (delete $storage[k] && webStorage.removeItem('ngStorage-' + k)); }
                            return $storage.$default(items);
                        }
    

    Hope this helps.

    opened by rortegax2 11
  • Comparison with AngularStorage and Angular-localForage?

    Comparison with AngularStorage and Angular-localForage?

    I'd appreciate a bit of documentation added to the README that compare these very similar solutions that overlap in functionality, especially the 'sweet spot' use case each addresses.

    opened by webmaven 9
  • Keep $localStorage in sync between tabs

    Keep $localStorage in sync between tabs

    I have a problem with two concurrently open tabs:

    1. I change something in tab 1, say $localStorage.myList
    2. If I'm $watching the same object ($scope.list = $localStorage.myList) in tab 2, the listener is triggered, but $localStorage.myList still contains the old value!

    I have noticed that the angular.element($window).bind('storage', function(event) {}) part is called in the second tab, but it never updates $storage!

    Can this be fixed? I think it can by simply recreating the $storage starting from the localStorage javascript object.

    opened by frapontillo 9
  • feat(webpack/browserify): final fix 😂

    feat(webpack/browserify): final fix 😂

    Hey @egilkh,

    First: Thanks for this! :)

    2nd: to enable the easy import like:

    angular.module('App', [
        require('angular-ui-router'),
        require('ngstorage')
    ]);
    

    You need to export the module name as string, not the module :)

    opened by robinboehm 8
  • TypeError: a.key is null

    TypeError: a.key is null

    I don't know if this is still supported (seems unlikely that I'll get some help), but I'll ask anyways.

    I have a large AngularJS project which implements ngStorage and, lately, we are getting a warning stating "TypeError: a.key is null". It has been a bit hard to go through whole project in order to detect where is it coming from.

    So guidance as to what causes this and what could be done to fix it would be greatly appreciated =)

    opened by filipegarrett 0
  • Dependency Vulnerabilities

    Dependency Vulnerabilities

    Hi there!

    Please update your referenced dependencies to the latest versions (+-70 Vulnerabilities are currently found).

    Thanks a lot in advance! Kind Regards CJ

    opened by CH-Chonsu 0
  • Fortify scan(Insecure Randomness)

    Fortify scan(Insecure Randomness)

    In line 1 of ngStorage.min.js When we did a fortify scan we are encountering an error stating Insecure Randomness.

    Insecure randomness errors occur when a function that can produce predictable values is used as a source of randomness in security-sensitive context.

    Help us solve the issue

    opened by mikesorsibin 0
  • Issue when changing document focus

    Issue when changing document focus

    I have 2 tabs open. On tab 1 I click login and the state changes in ~1-2 seconds. If I quickly focus the 2nd tab before the changes in tab 1 the ngStorage doesn't update due to !doc.hasFocus || !doc.hasFocus(). Why is this placed here?

    This is done in Chrome 71.0.3578.98 (Official Build) (64-bit)

    opened by prestontighe 0
  • BUG: On $reset if load the same values the Local Storage is clear.

    BUG: On $reset if load the same values the Local Storage is clear.

    Bug: Browser storage mantein clear when $localstorage.$reset and try to load the same data. $localstorage.$reset($localstorage); // Brower Local Storage are empty

    The cause: On $reset the _last$storage variable is not clear and this make that on $apply the conditon always is true: if (!angular.equals($storage, _last$storage))

    Fix (suggested):

                      $reset: function(items) {
                                for (var k in $storage) {
                                    '$' === k[0] || (delete $storage[k] && webStorage.removeItem(storageKeyPrefix + k));
                                }
                                _last$storage={}; 
                                return $storage.$default(items);
                            },
    
    opened by pdorgambide 1
  • Apply method called on the readme.md

    Apply method called on the readme.md

    I had an issue on IPADs because of the $apply method not being called. For some reason, it doesn`t persist the information if that method is not called on IPADs ( Safari and Chrome ).

    I thought it would make sense add that to the readme to avoid issues like that in the future.

    opened by felipegouveiae 0
Releases(0.3.11)
Owner
G. Kay Lee
Accomplished JavaScript artisan specializing in frontend architecture and web applications. 9+ years of professional experience.
G. Kay Lee
sessionStorage API which gracefully degrades to window.name & cookies when not available

sessionstorage The sessionStorage API is amazing and super useful when you need to store data temporarily in the browser. We used to abuse cookies for

null 22 Jul 25, 2022
An AngularJS module that gives you access to the browsers local storage with cookie fallback

angular-local-storage An Angular module that gives you access to the browsers local storage Table of contents: Get Started Video Tutorial Development

Gregory Pike 2.9k Dec 25, 2022
Browser storage interface for IndexedDB, WebSQL, LocalStorage, and in memory data with Schema and data validator.

Client Web Storage Browser storage interface for IndexedDB, WebSQL, LocalStorage, and in memory data with basic Schema and data validation. Installati

Before Semicolon 19 Sep 30, 2022
A script and resource loader for caching & loading files with localStorage

Basket.js is a script and resource loader for caching and loading scripts using localStorage ##Introduction for the Non-Developer Modern web applicati

Addy Osmani 3.4k Dec 30, 2022
:lock: Secure localStorage data with high level of encryption and data compression

secure-ls Secure localStorage data with high level of encryption and data compression. LIVE DEMO Features Secure data with various types of encryption

Varun Malhotra 602 Nov 30, 2022
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

localForage localForage is a fast and simple storage library for JavaScript. localForage improves the offline experience of your web app by using asyn

localForage 21.5k Jan 4, 2023
Vue.js localStorage plugin with types support

VueLocalStorage LocalStorage plugin inspired by Vue typed props which take a care of typecasting for Vue.js 1 and 2 with SSR support. Install npm inst

Alexander Avakov 669 Nov 29, 2022
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

localForage localForage is a fast and simple storage library for JavaScript. localForage improves the offline experience of your web app by using asyn

localForage 21.5k Jan 1, 2023
Simple window.localStorage, with type safety

mini-local-storage simple window.localStorage, with type safety example // localStorage.ts import { createLocalStorage } from "mini-local-storage";

Kipras Melnikovas 4 Jan 8, 2023
local storage wrapper for both react-native and browser. Support size controlling, auto expiring, remote data auto syncing and getting batch data in one query.

react-native-storage This is a local storage wrapper for both react native apps (using AsyncStorage) and web apps (using localStorage). ES6 syntax, pr

Sunny Luo 2.9k Dec 16, 2022
A lightweight vanilla ES6 cookies and local storage JavaScript library

?? CrumbsJS ?? A lightweight, intuitive, vanilla ES6 fueled JS cookie and local storage library. Quick Start Adding a single cookie or a local storage

null 233 Dec 13, 2022
Load and save cookies within your React application

react-cookie Universal cookies for React universal-cookie Universal cookies for JavaScript universal-cookie-express Hook cookies get/set on Express fo

Reactive Stack 2.4k Dec 30, 2022
A enhanced web storage with env support, expire time control, change callback and LRU storage clear strategy.

enhanced-web-storage A enhanced web storage with env support, expire time control, change callback and LRU storage clear strategy. How to Start import

Ziwen Mei 15 Sep 10, 2021
The perfect combination: local business shopping and crypto.

The perfect combination: local business shopping and crypto. Get passive income and support local businesses.

Mauricio Figueiredo 4 Mar 19, 2022
A javascript based module to access and perform operations on Linode object storage via code.

Linode Object Storage JS Module A javascript based module to access and perform operations on Linode object storage via code. Code Guardian Installing

Core.ai 3 Jan 11, 2022
Store your data in the world's fastest and most secure storage, powered by the blockchain technology⚡️

Store your data in the world's fastest and most secure storage, powered by the blockchain technology.

BlockDB 3 Mar 5, 2022
Expirable data storage based on localStorage and sessionStorage.

Expirable storage About The Project Expirable data storage based on localStorage and sessionStorage. Getting Started To get a local copy up and runnin

Wayfair Tech – Incubator 5 Oct 31, 2022
AngularJS SPA Template for Visual Studio is a project skeleton for a simple single-page web application (SPA) built with AngularJS, Bootstrap, and ASP.NET (MVC, Web Api, SignalR).

AngularJS SPA Template for Visual Studio This project is a skeleton for a simple single-page web application (SPA) built on top of the: AngularJS 1.2.

Kriasoft 105 Jun 18, 2022
Satyam Sharma 3 Jul 8, 2022
A web app designed to keep track of activities that are done and those that are and not done. Users can add, delete, mark as completed and update the activities. Built with Javscript, html, css and webpack.e your activites

ToDoListApp A web app designed to help web keep track of activities that are done and those that are still pending. Users can add, delete, mark as com

Francis Wayungi 6 Dec 23, 2022