Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/grevory/angular-local-storage
An AngularJS module that gives you access to the browsers local storage with cookie fallback
https://github.com/grevory/angular-local-storage
angular angularjs cookie javascript localstorage
Last synced: about 21 hours ago
JSON representation
An AngularJS module that gives you access to the browsers local storage with cookie fallback
- Host: GitHub
- URL: https://github.com/grevory/angular-local-storage
- Owner: grevory
- License: other
- Created: 2012-08-27T06:31:44.000Z (over 12 years ago)
- Default Branch: master
- Last Pushed: 2017-08-29T14:16:59.000Z (over 7 years ago)
- Last Synced: 2024-10-19T23:17:28.407Z (about 2 months ago)
- Topics: angular, angularjs, cookie, javascript, localstorage
- Language: JavaScript
- Homepage:
- Size: 325 KB
- Stars: 2,828
- Watchers: 110
- Forks: 585
- Open Issues: 65
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
- awesome-web-storage - angular-local-storage - An AngularJS module that gives access to the browsers local storage with cookie fallback. (awesome-web-storage [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) / Different Storage APIs)
- Resources - Module that gives access to the browsers local storage
README
angular-local-storage
=====================
An Angular module that gives you access to the browsers local storage[![NPM version][npm-image]][npm-url]
[![Build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![Dependency Status][david-image]][david-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]## Table of contents:
- [![Gitter][gitter-image]][gitter-url]
- [Get Started](#get-started)
- [Video Tutorial](https://www.youtube.com/watch?v=I4iB0kOSmx8)
- [Development](#development)
- [Configuration](#configuration)
- [setPrefix](#setprefix)
- [setStorageType](#setstoragetype)
- [setDefaultToCookie](#setdefaulttocookie)
- [setStorageCookie](#setstoragecookie)
- [setStorageCookieDomain](#setstoragecookiedomain)
- [setNotify](#setnotify)
- [Example](#configuration-example)
- [API Documentation](#api-documentation)
- [isSupported](#issupported)
- [changePrefix]
- [getStorageType](#getstoragetype)
- [set](#set)
- [get](#get)
- [keys](#keys)
- [remove](#remove)
- [clearAll](#clearall)
- [bind](#bind)
- [deriveKey](#derivekey)
- [length](#length)
- [cookie](#cookie)
- [isSupported](#cookieissupported)
- [set](#cookieset)
- [get](#cookieget)
- [remove](#cookieremove)
- [clearAll](#cookieclearall)## Get Started
**(1)** You can install angular-local-storage using 3 different ways:
**Git:**
clone & build [this](https://github.com/grevory/angular-local-storage.git) repository
**Bower:**
```bash
$ bower install angular-local-storage --save
```
**npm:**
```bash
$ npm install angular-local-storage
```
**(2)** Include `angular-local-storage.js` (or `angular-local-storage.min.js`) from the [dist](https://github.com/grevory/angular-local-storage/tree/master/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:
```html
...
...
var myApp = angular.module('myApp', ['LocalStorageModule']);
...```
## Configuration
### setPrefix
You could set a prefix to avoid overwriting any local storage variables from the rest of your app
**Default prefix:** `ls.`
```js
myApp.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('yourAppName');
});
```
### setStorageType
You could change web storage type to localStorage or sessionStorage
**Default storage:** `localStorage`
```js
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`
```js
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`
```js
myApp.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setStorageCookie(45, '', 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**
```js
myApp.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setStorageCookieDomain('');
});
```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"
```js
myApp.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setNotify(true, true);
});
```
### Configuration Example
Using all together
```js
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`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
if(localStorageService.isSupported) {
//...
}
//...
});
```
### setPrefix
Change the local storage prefix during execution
**Returns:** `Null`
```js
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`
```js
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`
```js
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`
```js
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`
```js
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`
```js
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.
```js
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'));
});
}
//...
});
```
```html
{{property}}
update
unbind
```### deriveKey
Return the derive key
**Returns** `String`
```js
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`
```js
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`
```js
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`
```js
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
```js
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](https://www.w3.org/TR/csp-cookies/#grammardef-secure)
```js
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`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function getItem(key) {
return localStorageService.cookie.get(key);
}
//...
});
```
### cookie.remove
Remove directly value from a cookie.
**Returns:** `Boolean`
```js
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`
```js
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:
```sh
$ git clone https://github.com//angular-local-storage.git
$ npm install
$ bower install
```
Run the tests:
```sh
$ grunt test
```
**Deploy:**
Run the build task, update version before(bower,package)
```sh
$ npm version patch|minor|major
$ grunt dist
$ git commit [message]
$ git push origin master --tags
```[npm-image]: https://img.shields.io/npm/v/angular-local-storage.svg?style=flat-square
[npm-url]: https://npmjs.org/package/angular-local-storage
[travis-image]: https://img.shields.io/travis/grevory/angular-local-storage.svg?style=flat-square
[travis-url]: https://travis-ci.org/grevory/angular-local-storage
[coveralls-image]: https://img.shields.io/coveralls/grevory/angular-local-storage.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/grevory/angular-local-storage
[david-image]: http://img.shields.io/david/grevory/angular-local-storage.svg?style=flat-square
[david-url]: https://david-dm.org/grevory/angular-local-storage
[license-image]: http://img.shields.io/npm/l/angular-local-storage.svg?style=flat-square
[license-url]: LICENSE
[downloads-image]: http://img.shields.io/npm/dm/angular-local-storage.svg?style=flat-square
[downloads-url]: https://npmjs.org/package/angular-local-storage
[gitter-image]: https://badges.gitter.im/Join%20Chat.svg
[gitter-url]: https://gitter.im/grevory/angular-local-storage?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge