angular-local-storage
An AngularJS module that gives you access to the browsers local storage with cookie fallback
Top Related Projects
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.
Cross-browser storage for all use cases, used across the web.
Simple and fast JSON database
A localStorage-based memcache-inspired client-side caching library.
Quick Overview
Angular-local-storage is a lightweight Angular module that provides a convenient wrapper for working with the browser's local storage. It offers an easy-to-use service for storing and retrieving data in local storage, with added features like prefix management and serialization/deserialization of objects.
Pros
- Simple API for interacting with local storage
- Supports automatic serialization and deserialization of objects
- Allows setting a prefix for all keys to avoid conflicts
- Provides fallback to cookies if local storage is not available
Cons
- Limited to Angular applications
- No built-in encryption for sensitive data
- Lacks advanced features like expiration or quota management
- Not actively maintained (last update was in 2019)
Code Examples
Setting and getting a value:
import { LocalStorageService } from 'angular-local-storage';
constructor(private localStorageService: LocalStorageService) {}
// Set a value
this.localStorageService.set('key', 'value');
// Get a value
const value = this.localStorageService.get('key');
Storing and retrieving an object:
const user = { name: 'John', age: 30 };
// Store object
this.localStorageService.set('user', user);
// Retrieve object
const storedUser = this.localStorageService.get('user');
console.log(storedUser.name); // Output: John
Using a custom prefix:
// In your app module
LocalStorageModule.forRoot({
prefix: 'myApp',
storageType: 'localStorage'
})
// Usage
this.localStorageService.set('key', 'value');
// Stored as: myApp.key
Getting Started
-
Install the package:
npm install angular-local-storage
-
Import the module in your
app.module.ts
:import { LocalStorageModule } from 'angular-local-storage'; @NgModule({ imports: [ LocalStorageModule.forRoot({ prefix: 'myApp', storageType: 'localStorage' }) ] }) export class AppModule { }
-
Inject and use the service in your components:
import { LocalStorageService } from 'angular-local-storage'; constructor(private localStorageService: LocalStorageService) {} saveData() { this.localStorageService.set('key', 'value'); } getData() { return this.localStorageService.get('key'); }
Competitor Comparisons
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.
Pros of localForage
- Broader browser support, including IndexedDB, WebSQL, and localStorage
- Asynchronous API with Promise support
- Not tied to a specific framework, can be used with any JavaScript project
Cons of localForage
- Larger file size and potentially more complex setup
- May be overkill for simple storage needs
- No built-in Angular-specific features or integrations
Code Comparison
angular-local-storage:
angular.module('YourApp', ['LocalStorageModule'])
.config(function (localStorageServiceProvider) {
localStorageServiceProvider.setPrefix('myApp');
});
localForage:
localforage.config({
name: 'myApp',
storeName: 'keyvaluepairs'
});
Key Differences
- Framework dependency: angular-local-storage is specifically designed for AngularJS, while localForage is framework-agnostic.
- Storage mechanisms: localForage supports multiple storage backends, while angular-local-storage primarily uses localStorage.
- API style: angular-local-storage provides a more Angular-centric API, whereas localForage offers a Promise-based API.
- Performance: localForage may offer better performance for large datasets due to its use of IndexedDB when available.
- Community and maintenance: localForage has a larger community and more frequent updates, potentially offering better long-term support.
When choosing between these libraries, consider your project's specific needs, framework requirements, and desired features to make the best decision for your use case.
Cross-browser storage for all use cases, used across the web.
Pros of store.js
- Framework-agnostic, can be used with any JavaScript project
- Supports a wider range of storage engines (localStorage, sessionStorage, cookies, etc.)
- Smaller file size and simpler API
Cons of store.js
- Lacks built-in Angular integration
- No built-in encryption or security features
- Less active development and community support
Code Comparison
store.js:
store.set('user', { name: 'Marcus' })
store.get('user')
store.remove('user')
angular-local-storage:
localStorageService.set('user', { name: 'Marcus' });
localStorageService.get('user');
localStorageService.remove('user');
Summary
store.js is a versatile, lightweight storage solution that works across various JavaScript projects. It offers flexibility in storage engine selection but lacks specific Angular integration. angular-local-storage, on the other hand, is tailored for Angular applications, providing seamless integration and potentially more Angular-specific features.
The choice between the two depends on the project requirements. For Angular-specific projects, angular-local-storage might be more suitable due to its integration. For broader JavaScript applications or when working with multiple frameworks, store.js could be the better option due to its framework-agnostic nature and support for various storage engines.
Simple and fast JSON database
Pros of lowdb
- More versatile, can be used with Node.js and in the browser
- Supports multiple adapters (JSON file, Memory, LocalStorage)
- Provides a lightweight database with chainable query API
Cons of lowdb
- Not specifically designed for Angular applications
- May require more setup and configuration for use in Angular projects
- Less Angular-specific features and integrations
Code Comparison
lowdb:
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('db.json')
const db = low(adapter)
db.defaults({ posts: [] })
.write()
angular-local-storage:
angular.module('YourApp', ['LocalStorageModule'])
.config(function (localStorageServiceProvider) {
localStorageServiceProvider.setPrefix('myApp');
})
.controller('MainCtrl', function($scope, localStorageService) {
localStorageService.set('key', 'value');
});
Summary
lowdb is a more general-purpose lightweight database solution that can be used in various JavaScript environments, including the browser and Node.js. It offers flexibility with multiple adapters and a chainable query API. However, it may require more setup for use in Angular projects.
angular-local-storage is specifically designed for Angular applications, providing seamless integration and Angular-specific features. It focuses on localStorage manipulation and is easier to set up in Angular projects, but it's limited to browser environments and doesn't offer the same database-like functionality as lowdb.
Choose based on your project requirements: lowdb for a more versatile, database-like solution, or angular-local-storage for simpler localStorage management in Angular applications.
A localStorage-based memcache-inspired client-side caching library.
Pros of lscache
- Framework-agnostic, can be used with any JavaScript project
- Includes built-in expiration functionality
- Smaller codebase, potentially easier to maintain
Cons of lscache
- Lacks Angular-specific features and integration
- Does not support namespacing for stored items
- May require more manual configuration for complex use cases
Code Comparison
lscache:
lscache.set('key', 'value', 60); // Store for 60 minutes
var value = lscache.get('key');
lscache.remove('key');
angular-local-storage:
localStorageService.set('key', 'value');
var value = localStorageService.get('key');
localStorageService.remove('key');
Key Differences
- lscache is a standalone library, while angular-local-storage is specifically designed for Angular applications
- angular-local-storage provides more extensive features like cookie fallback, event broadcasting, and namespacing
- lscache focuses on simplicity and includes built-in expiration functionality
- angular-local-storage offers tighter integration with Angular's dependency injection system
Use Cases
- Choose lscache for lightweight, framework-agnostic local storage with built-in expiration
- Opt for angular-local-storage when working with Angular projects that require more advanced features and integration
Community and Maintenance
- Both projects are open-source and available on GitHub
- angular-local-storage has a larger user base and more frequent updates
- lscache is more focused and has a smaller, but active community
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
angular-local-storage
An Angular module that gives you access to the browsers local storage
Table of contents:
- Get Started
- Video Tutorial
- Development
- Configuration
- setPrefix
- setStorageType
- setDefaultToCookie
- setStorageCookie
- setStorageCookieDomain
- setNotify
- Example
- API Documentation
- isSupported
- [changePrefix]
- getStorageType
- set
- get
- keys
- remove
- clearAll
- bind
- deriveKey
- length
- cookie
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
Top Related Projects
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.
Cross-browser storage for all use cases, used across the web.
Simple and fast JSON database
A localStorage-based memcache-inspired client-side caching library.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot