An AngularJS module that gives you access to the browsers local storage with cookie fallback

Overview

angular-local-storage

An Angular module that gives you access to the browsers local storage

NPM version Build status Test coverage Dependency Status License Downloads

Table of contents:

Get Started

(1) You can install angular-local-storage using 3 different ways:
Git: clone & build this repository
Bower:

$ bower install angular-local-storage --save

npm:

$ npm install angular-local-storage

(2) Include angular-local-storage.js (or angular-local-storage.min.js) from the dist directory in your index.html, after including Angular itself.

(3) Add 'LocalStorageModule' to your main module's list of dependencies.

When you're done, your setup should look similar to the following:

<!doctype html>
<html ng-app="myApp">
<head>

</head>
<body>
    ...
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
    <script src="bower_components/js/angular-local-storage.min.js"></script>
    ...
    <script>
        var myApp = angular.module('myApp', ['LocalStorageModule']);

    </script>
    ...
</body>
</html>

Configuration

setPrefix

You could set a prefix to avoid overwriting any local storage variables from the rest of your app
Default prefix: ls.<your-key>

myApp.config(function (localStorageServiceProvider) {
  localStorageServiceProvider
    .setPrefix('yourAppName');
});

setStorageType

You could change web storage type to localStorage or sessionStorage
Default storage: localStorage

myApp.config(function (localStorageServiceProvider) {
  localStorageServiceProvider
    .setStorageType('sessionStorage');
});

setDefaultToCookie

If localStorage is not supported, the library will default to cookies instead. This behavior can be disabled.
Default: true

myApp.config(function (localStorageServiceProvider) {
  localStorageServiceProvider
    .setDefaultToCookie(false);
});

setStorageCookie

Set cookie options (usually in case of fallback)
expiry: number of days before cookies expire (0 = session cookie). default: 30
path: the web path the cookie represents. default: '/'
secure: whether to store cookies as secure. default: false

myApp.config(function (localStorageServiceProvider) {
  localStorageServiceProvider
    .setStorageCookie(45, '<path>', false);
});

setStorageCookieDomain

Set the cookie domain, since this runs inside a the config() block, only providers and constants can be injected. As a result, $location service can't be used here, use a hardcoded string or window.location.
No default value

myApp.config(function (localStorageServiceProvider) {
  localStorageServiceProvider
    .setStorageCookieDomain('<domain>');
});

For local testing (when you are testing on localhost) set the domain to an empty string ''. Setting the domain to 'localhost' will not work on all browsers (eg. Chrome) since some browsers only allow you to set domain cookies for registry controlled domains, i.e. something ending in .com or so, but not IPs or intranet hostnames like localhost.

setNotify

Configure whether events should be broadcasted on $rootScope for each of the following actions:
setItem , default: true, event "LocalStorageModule.notification.setitem"
removeItem , default: false, event "LocalStorageModule.notification.removeitem"

myApp.config(function (localStorageServiceProvider) {
  localStorageServiceProvider
    .setNotify(true, true);
});

Configuration Example

Using all together

myApp.config(function (localStorageServiceProvider) {
  localStorageServiceProvider
    .setPrefix('myApp')
    .setStorageType('sessionStorage')
    .setNotify(true, true)
});

API Documentation

isSupported

Checks if the browser support the current storage type(e.g: localStorage, sessionStorage). Returns: Boolean

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  if(localStorageService.isSupported) {
    //...
  }
  //...
});

setPrefix

Change the local storage prefix during execution Returns: Null

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  localStorageService.setPrefix('newPrefix');
  //...
});

getStorageType

Returns: String

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  var storageType = localStorageService.getStorageType(); //e.g localStorage
  //...
});

You can also dynamically change storage type by passing the storage type as the last parameter for any of the API calls. For example: localStorageService.set(key, val, "sessionStorage");

set

Directly adds a value to local storage.
If local storage is not supported, use cookies instead.
Returns: Boolean

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  function submit(key, val) {
   return localStorageService.set(key, val);
  }
  //...
});

get

Directly get a value from local storage.
If local storage is not supported, use cookies instead.
Returns: value from local storage

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  function getItem(key) {
   return localStorageService.get(key);
  }
  //...
});

keys

Return array of keys for local storage, ignore keys that not owned.
Returns: value from local storage

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  var lsKeys = localStorageService.keys();
  //...
});

remove

Remove an item(s) from local storage by key.
If local storage is not supported, use cookies instead.
Returns: Boolean

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  function removeItem(key) {
   return localStorageService.remove(key);
  }
  //...
  function removeItems(key1, key2, key3) {
   return localStorageService.remove(key1, key2, key3);
  }
});

clearAll

Remove all data for this app from local storage.
If local storage is not supported, use cookies instead.
Note: Optionally takes a regular expression string and removes matching.
Returns: Boolean

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  function clearNumbers(key) {
   return localStorageService.clearAll(/^\d+$/);
  }
  //...
  function clearAll() {
   return localStorageService.clearAll();
  }
});

bind

Bind $scope key to localStorageService. Usage: localStorageService.bind(scope, property, value[optional], key[optional]) key: The corresponding key used in local storage Returns: deregistration function for this listener.

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  localStorageService.set('property', 'oldValue');
  $scope.unbind = localStorageService.bind($scope, 'property');

  //Test Changes
  $scope.update = function(val) {
    $scope.property = val;
    $timeout(function() {
      alert("localStorage value: " + localStorageService.get('property'));
    });
  }
  //...
});
<div ng-controller="MainCtrl">
  <p>{{property}}</p>
  <input type="text" ng-model="lsValue"/>
  <button ng-click="update(lsValue)">update</button>
  <button ng-click="unbind()">unbind</button>
</div>

deriveKey

Return the derive key Returns String

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  localStorageService.set('property', 'oldValue');
  //Test Result
  console.log(localStorageService.deriveKey('property')); // ls.property
  //...
});

length

Return localStorageService.length, ignore keys that not owned. Returns Number

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  var lsLength = localStorageService.length(); // e.g: 7
  //...
});

Cookie

Deal with browser's cookies directly.

cookie.isSupported

Checks if cookies are enabled in the browser. Returns: Boolean

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  if(localStorageService.cookie.isSupported) {
    //...
  }
  //...
});

cookie.set

Directly adds a value to cookies.
Note: Typically used as a fallback if local storage is not supported.
Returns: Boolean

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  function submit(key, val) {
   return localStorageService.cookie.set(key, val);
  }
  //...
});

Cookie Expiry Pass a third argument to specify number of days to expiry

    localStorageService.cookie.set(key,val,10)

sets a cookie that expires in 10 days. Secure Cookie Pass a fourth argument to set the cookie as secure W3C

    localStorageService.cookie.set(key,val,null,false)

sets a cookie that is secure.

cookie.get

Directly get a value from a cookie.
Returns: value from local storage

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  function getItem(key) {
   return localStorageService.cookie.get(key);
  }
  //...
});

cookie.remove

Remove directly value from a cookie.
Returns: Boolean

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  function removeItem(key) {
   return localStorageService.cookie.remove(key);
  }
  //...
});

cookie.clearAll

Remove all data for this app from cookie.
Returns: Boolean

myApp.controller('MainCtrl', function($scope, localStorageService) {
  //...
  function clearAll() {
   return localStorageService.cookie.clearAll();
  }
});

Check out the full demo at http://gregpike.net/demos/angular-local-storage/demo.html

Development:

  • Don't forget about tests.
  • If you're planning to add some feature please create an issue before.

Clone the project:

$ git clone https://github.com/<your-repo>/angular-local-storage.git
$ npm install
$ bower install

Run the tests:

$ grunt test

Deploy:
Run the build task, update version before(bower,package)

$ npm version patch|minor|major
$ grunt dist
$ git commit [message]
$ git push origin master --tags
Comments
  • added function parameter for secure cookies, added test, added api ex…

    added function parameter for secure cookies, added test, added api ex…

    added function parameter in localstorageservice.cookie.set() for secure cookies client side using the "secure" attribute mentioned in the W3C CSP Headers Spec (server side): https://www.w3.org/TR/csp-cookies/#grammardef-secure

    added tests and fixed some of the README.md

    pr-in-review 
    opened by ry8806 30
  • Add (default value) as an optional parameter to the Get function.

    Add (default value) as an optional parameter to the Get function.

    Add the ability to set the default value to the get function like the following:

    localStorageService.get('some_key','def_val');
    

    Old code

        var autoLogin = localStorageService.get('Auth.autoLogin');
    
        if (autoLogin == null) {
            localStorageService.set('Auth.autoLogin', false);
            autoLogin = false;
        }
    

    New code

        var autoLogin = localStorageService.get('Auth.autoLogin',false);
    
    opened by eymen-elkum 14
  • add setStorageType from localStorageService

    add setStorageType from localStorageService

    A lot of users and me need to change storage type according to application behaviors, so I add setStorageType method directly callable from localStorageService. Maybe there are better solution (for example, give a storageType parameter directly in set method...), but I think this can help people.

    pr-needs-feedback 
    opened by william57m 14
  • setPrefix in localStorageService, so we can switch prefix during execution

    setPrefix in localStorageService, so we can switch prefix during execution

    Provide method to set prefix after config

    // angular-local-storage.js var getPrefix = function() { return prefix; }

    var setPrefix = function(val) { prefix = val;

    // DUPLICATE CODE line 104 => put in a function ? // If there is a prefix set in the config lets use that with an appended period for readability if (prefix.substr(-1) !== '.') { prefix = !!prefix ? prefix + '.' : ''; }

    }

    return { getPrefix: getPrefix, setPrefix: setPrefix, isSupported: browserSupportsLocalStorage,

    // TEST in app.js // console.log("localStorageService prefix"); console.log(localStorageService.getPrefix()); localStorageService.setPrefix("mynewprefix"); console.log(localStorageService.getPrefix());

    enhancement pr-needs-feedback 
    opened by lorenzyannick 13
  • Added changePrefix for multi-app usage.

    Added changePrefix for multi-app usage.

    In an enterprise environment, local storage may be used as a dependency for multiple applications. Forcing the prefix to be set by the encapsulating enterprise framework prevents developers from overwriting each others local storage.

    pr-needs-feedback 
    opened by ChicagoDave 11
  • Watch for changes in local storage

    Watch for changes in local storage

    When you call localStorageService.bind, it would be nice if it then listened for changes to the local storage key it binds to, and updated the bound object (as suggested by @lieryan in #131). This can be done by registering an event listener for the "storage" event. PR incoming.

    pr-needs-feedback 
    opened by DaveWM 11
  • Values 'set' as number are changed to string after 'get'

    Values 'set' as number are changed to string after 'get'

    When I made a round trip (set and then get) my numeric values came back as strings.

    localStorageService.set("page_number", n); // n === 1
    n = localStorageService.get("page_number"); // n === "1"
    

    np, I fixed it with:

    n = parseInt(localStorageService.get("page_number"), 10);
    

    but I thinkit would be better to preserve the basic JSON types.

    bug 
    opened by nmorse 11
  • Allow true dynamic storage type on transaction

    Allow true dynamic storage type on transaction

    As per my comment in #320, I don't think that the solution quite cut the mustard as it would permanently change the storage type for all further transactions.

    My addition to the solution is to restore the previous storage type after a transaction.

    The use case that is currently failing is:

    // Assume the default storage is localStorage
    
    // Sets the status to be true in sessionStorage
    localStorageService.set('status', true, 'sessionStorage');
    
    // Sets the status to be false in sessionStorage
    // I would expect this to inherit the default storage type
    localStorageService.set('status', false);
    
    opened by benhoIIand 10
  • New version completely breaks my system - definitely not a minor version bump

    New version completely breaks my system - definitely not a minor version bump

    From the looks of the minor version bump, one would think that only minor updates were done but when I checked out the commit history, I saw that the entire module was changed. Including a commit: https://github.com/grevory/angular-local-storage/commit/8a738f918e2407640dfe0f57ad01851b16d33cb2 that features over 900 line code additions and 800 lines of code deletions. (difference between versions for reference: https://github.com/grevory/angular-local-storage/compare/0.2.3...0.2.4)

    Is there a way you guys can bump this a major version? The update broke all of my tests and functionality across my application since I was using the ~ for versioning (meaning, it can pull in minor version changes).

    Just for reference:

    I'm using Browserify + Babel to compile my code and was using angular-local-storage via browserify-shim over Bower.

    bug 
    opened by AntJanus 9
  • Added in deep compare option for bind and documented bind feature

    Added in deep compare option for bind and documented bind feature

    First off, thanks for making a great localstorage module. I especially liked that it basically worked with everything, arrays and all, out of the box.

    I had a complicated array structure that I wanted to store and as per http://stackoverflow.com/questions/14712089/how-to-deep-watch-an-array-in-angularjs the advice was to use $watch instead of $watchCollection to deal with the deep comparision that I needed.

    It's a relatively small change and I hope my documentation on bind is helpful to others as well.

    pr-needs-work 
    opened by kjlubick 9
  • Error: 'undefined' is not an object (evaluating '$document.cookie.split')

    Error: 'undefined' is not an object (evaluating '$document.cookie.split')

    Get this error when open my site on iPhone:

    Error: 'undefined' is not an object (evaluating '$document.cookie.split')
    

    If I try to get $document.cookie.split function locally — get the same error too.

    Fix this by removing '$' from '$document': in line 280 and in line 300:

    var cookies = document.cookie.split(';');
    

    Don't know if this is best solution, but it works.

    opened by applecat 9
  • Shared Service versus Session Storage

    Shared Service versus Session Storage

    More of a question than an issue. What's the point of "session" storage when we can share state using Angular services (singletons available across the application but only during a browser "session")? Thoughts?

    opened by cogitaria-admin 1
  • Getter for prefix

    Getter for prefix

    Please, provide getter for storage prefix. This could be useful for example in window listeners $window.addEventListener('storage', function (event) { if (event.key === localStorageService.prefix + 'logout-event') { factory.logout() } });

    opened by maksimradzevich 0
  • addToLocalStorage should not fallback to cookies on exception

    addToLocalStorage should not fallback to cookies on exception

    Currently addToLocalStorage() catches exceptions from webStorage.setItem() and falls back to writing to cookies if an exception happened (code). This seems wrong:

    • It doesn't check self.defaultToCookie before doing so.
    • Since browserSupportsLocalStorage is true, there's no matching code in getFromLocalStorage() to read the saved value.

    In practice this leads to the following problem: if the local storage limit is exceeded, the data starts being written to cookies, which quickly overflows the cookie size limits and causes 400.

    opened by eltoder 0
  • setPrefix in controller doesn't append a dot

    setPrefix in controller doesn't append a dot

    Hi,

    I'm not sure whether this is intended, but when setting a prefix in the controller instead of as a config definition, you have to manually set a dot at the end of the prefix.

    Examples:

    This will result in the prefix your-prefix.

    .config(function (localStorageServiceProvider) {
      localStorageServiceProvider
    	.setPrefix('your-prefix')
    })´
    

    This will result in the prefix your-prefix

    .controller('example-controller', function (localStorageService) {
      localStorageService.setPrefix('your-prefix');
    })
    
    opened by jastend 0
  • JavaScript issue in IE12 or lower

    JavaScript issue in IE12 or lower

    Hi, some errors in javascript

    Versions:

    • Angular: 1.6.6
    • Angular Local Storage: 0.7.1
    • Browser: Internet Explorer 11

    Case: Inside callback function, localStorage plugin call "finally" clause after try catch. This not work in IE 12- For solve this, please use try catch correcly -if is possible- and return in every function a default object if it is fail.

    Example:

    Current code

    // Directly adds a value to local storage // If local storage is not available in the browser use cookies // Example use: localStorageService.add('library','angular'); var addToLocalStorage = function (key, value, type) { var previousType = getStorageType();

        try {
          setStorageType(type);
    
          // Let's convert undefined values to null to get the value consistent
          if (isUndefined(value)) {
            value = null;
          } else {
            value = toJson(value);
          }
    
          // If this browser does not support local storage use cookies
          if (!browserSupportsLocalStorage && self.defaultToCookie || self.storageType === 'cookie') {
            if (!browserSupportsLocalStorage) {
              $rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
            }
    
            if (notify.setItem) {
              $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'});
            }
            return addToCookies(key, value);
          }
    
          try {
            if (webStorage) {
              webStorage.setItem(deriveQualifiedKey(key), value);
            }
            if (notify.setItem) {
              $rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: self.storageType});
            }
          } catch (e) {
            $rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
            return addToCookies(key, value);
          }
          return true;
        } finally {
          setStorageType(previousType);
        }
      };
    

    Working code

    // Directly adds a value to local storage // If local storage is not available in the browser use cookies // Example use: localStorageService.add('library','angular'); var addToLocalStorage = function (key, value, type) {

      var previousType = getStorageType();
      var result = false;
    
      try {
      
      	setStorageType(type);
    
      	// Let's convert undefined values to null to get the value consistent
      	if (isUndefined(value)) {
      		value = null;
      	} 
      	else {
      		value = toJson(value);
      	}
    
      	// If this browser does not support local storage use cookies
      	if (!browserSupportsLocalStorage && self.defaultToCookie || self.storageType === 'cookie') {
      		if (!browserSupportsLocalStorage) {
      			$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
      		}
    
      		if (notify.setItem) {
      			$rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'});
      		}
      		
      		result = addToCookies(key, value);
      	}
      	else {
      		try {
      			
      			if (webStorage) {
      				webStorage.setItem(deriveQualifiedKey(key), value);
      			}
      			if (notify.setItem) {
      				$rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: self.storageType});
      			}
      			result = true;
      		} 
      		catch (e) {
      			
      			$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
      			result = addToCookies(key, value);
      		}
      	}
      }
      catch (e) { 
      	result = false;
      }
      finally { 
      	setStorageType(previousType);
      }
      
      return result;
    

    };

    thanks

    opened by TemitaTom 2
Releases(0.1.4)
localStorage and sessionStorage done right for AngularJS.

ngStorage An AngularJS module that makes Web Storage working in the Angular Way. Contains two services: $localStorage and $sessionStorage. Differences

G. Kay Lee 2.3k Nov 26, 2022
Cross domain local storage, with permissions

Cross domain local storage, with permissions. Enables multiple browser windows/tabs, across a variety of domains, to share a single localStorage. Feat

Zendesk 2.2k Jan 6, 2023
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
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 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
No longer maintained, superseded by JS Cookie:

IMPORTANT! This project was moved to https://github.com/js-cookie/js-cookie, check the discussion. New issues should be opened at https://github.com/j

Klaus Hartl 8.6k Jan 5, 2023
JavaScript Client-Side Cookie Manipulation Library

Cookies.js Cookies.js is a small client-side javascript library that makes managing cookies easy. Features Browser Compatibility Getting the Library U

Scott Hamper 1.8k Oct 7, 2022
京东快速提取 cookie 工具 golang版本

说明 v1.x 版本(tag) 本地运行,本地提取 京东的cookie 本地提取工具(小白专用) 双击exe文件,运行服务,后用本地的浏览器打开 http://127.0.0.1:29099 来辅助提取你的cookie v2.x 版本(tag) 服务器运行,客户端自行扫码提取,服务端自动更新cook

scjtqs 72 Aug 25, 2021
JDsms Cookie

京东短信获取Cookie PHP 环境运行(请确定运行环境). 自行修改 /api/sendNotify.php 里的 企业微信推送 参数 /images目录下 wx.png和qq.png 替换自己微信和QQ群 二维码图片 自用 仅用于测试和学习研究,禁止用于商业用途,您必须在下载后的24小时内从计

null 2 Feb 14, 2022
Vanilla JS that seamlessly add a notice for the European Cookie Law to any website

Notice: CookieNoticeJS is not under active development for the time being (and not GDPR compliant for what I know). Check AOEPeople fork instead. Cook

Alessandro Benoit 44 Aug 26, 2022
Lightweight Angular module for access to cookies

angular-cookie Lightweight Angular module for access to cookies Installation You can install angular-cookie via bower bower install angular-cookie Ot

Ivan Pusic 269 Oct 5, 2022
:sunglasses: Everything you need to know about Client-side Storage.

awesome-web-storage Everything you need to know about Client-side Storage. Table of Contents Introduction Browser Support Cookies Pros Cons API Useful

Varun Malhotra 420 Dec 12, 2022
This is an upload script which allows you to upload to web3 storage using JS.

This is an upload script which allows you to upload to web3 storage using JS. first make sure to run npm install on the directory run script using nod

null 1 Dec 24, 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
Cross-browser storage for all use cases, used across the web.

Store.js Cross-browser storage for all use cases, used across the web. Store.js has been around since 2010 (first commit, v1 release). It is used in p

Marcus Westin 13.9k Dec 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 4, 2023
JS / CSS / files loader + key/value storage

bag.js - JS / CSS loader + KV storage bag.js is loader for .js / .css and other files, that uses IndexedDB/ WebSQL / localStorage for caching. Conside

Nodeca 86 Nov 28, 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
⁂ The simple file storage service for IPFS & Filecoin

⁂ web3.storage The simple file storage service for IPFS & Filecoin. Getting started This project uses node v16 and npm v7. It's a monorepo that use np

Web3 Storage 423 Dec 25, 2022