原文:https://github.com/grevory/angular-local-storage#api-documentation

Get Started

(1)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: localStoragesessionStorage). Returns: Boolean

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

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

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: localStoragesessionStorage). Returns: Boolean

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

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
//本地缓存操作
$scope.localSave = app.localSave = function (key,value) {
localStorageService.set(key,value);
localStorageService.cookie.set(key,value); };
$scope.localGet = app.localGet = function (key) {
return localStorageService.get(key) ||
localStorageService.cookie.get(key);
};
$scope.localRemove = app.localRemove = function (key) {
localStorageService.remove(key);
localStorageService.cookie.remove(key);
};
$scope.urlGet = app.urlGet = function (key) {
var url_pid=window.location.search.substring(1);
var pairs = url_pid.split("&");
var urlinfo={};
for(var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf('=');
urlinfo[pairs[i].substring(0,pos)]=pairs[i].substring(pos+1);
}
return urlinfo[key]; };
$scope.sessionGet = app.sessionGet = function(key){
if(window.sessionStorage){
var item = window.sessionStorage[key];
if(item){
return JSON.parse(item);
}else{
return item;
}
}else{
return $scope.localGet(key);
}
return undefined;
}
$scope.sessionSave = app.sessionSave = function(key,value){
if(window.sessionStorage){
window.sessionStorage[key] = angular.toJson(value);
}else{
$scope.localSave(key,value);
}
}
$scope.sessionRemove = app.sessionRemove = function(key){
if(window.sessionStorage){
window.sessionStorage[key] = undefined;
}else{
$scope.localRemove(key);
}
}
 

本地存储 cookie,session,localstorage( 二)angular-local-storage的更多相关文章

  1. 本地存储 cookie,session,localstorage( 一)基本概念及原生API

    http://www.w3school.com.cn/html5/html_5_webstorage.asp http://adamed.iteye.com/blog/1698740 localSto ...

  2. jquery访问浏览器本地存储cookie,localStorage和sessionStorage

    前言:cookie,localStorage和sessionStorage都是浏览器本地存储数据的地方,其用法不尽相同:总结一下基本的用法. 一.cookie 定义: 存储在本地,容量最大4k,在同源 ...

  3. 本地存储常用方式 localStorage, sessionStorage,cookie 的区别 和 服务器存储session

    本地存储:把一些信息存储到客户端本地(主要目的有很多,其中有一个就是实现多页面之间的信息共享)       1. 离线缓存(xxx.manifest)  H5处理离线缓存还是存在一些硬伤的,所以真实项 ...

  4. 本地存储sessionStorage 、 localStorage 、cookie整理

    sessionStorage . localStorage .cookie 的区别 sessionStorage 和 localStorage 是HTML5 Web Storage API 提供的,可 ...

  5. H5新特性 本地存储---cookie localStorage sessionStorage

    本地存储的作用 :避免登录网站时,用户在页面浏览时重复登录,也可以实现快速登录,一段时间内保存用户的登录效果,提高页面访问速率 在html5中提供三种数据持久化操作的方法: 1.cookie 可看作是 ...

  6. 地理位置(navigation.geolocation)与本地存储(seessionStorage、localStorage)

    一.地理位置( geolocation ): navigator.geolocation对象: 1.单次请求: //navigator.geolocation.getCurrentPosition( ...

  7. 常用的本地存储-----cookie篇

    1.引言 随着浏览器的处理能力不断增强,越来越多的网站开始考虑将数据存储在「客户端」,那么久不得不谈本地存储了. 本地存储的好处: 一是避免取回数据前页面一片空白,如果不需要最新数据也可以减少向服务器 ...

  8. javascript的本地存储 cookies、localStorage

    一.cookies 本地存储 首先是常用的cookies方法,网上有很多相关的代码以及w3cSchool cookies. // 存储cookies function setCookie(name,v ...

  9. 浏览器存储(cookie、localStorage、sessionStorage)

    互联网早期浏览器是没有状态维护,这个就导致一个问题就是服务器不知道浏览器的状态,无法判断是否是同一个浏览器.这样用户登录.购物车功能都无法实现,Lou Montulli在1994年引入到web中最终纳 ...

随机推荐

  1. NServiceBus 概况

    NServiceBus 概况 NServiceBus 概况 NServiceBus 被设计用来组合面向业务的服务,它并不是用来替代诸如 WCF 一类的RPC技术. NServiceBus 不只包含通信 ...

  2. ASP.NET MVC路由(5)

    ASP.NET MVC路由(五) 前言 前面的篇幅讲解了MVC中的路由系统,只是大概的一个实现流程,让大家更清晰路由系统在MVC中所做的以及所在的位置,通过模糊的概念描述.思维导图没法让您看到路由的实 ...

  3. 使用POI导出excel

    引言:对于excel的导出,首先是将数据写到WorkBook中,然后将book以流的形式写出即可,看代码: public void exportResultInfo(String fileName,S ...

  4. 使用Json实体类构建菜单数据

    基于MVC4+EasyUI的Web开发框架经验总结(3)- 使用Json实体类构建菜单数据 最近花了不少时间在重构和进一步提炼我的Web开发框架上,力求在用户体验和界面设计方面,和Winform开发框 ...

  5. IOS UI 第三篇:基本UI

    工厂模式:   .h文件:   #import <Foundation/Foundation.h>typedef enum{    QFRed,    QFYellow,    QFBlu ...

  6. AngularJS框架速写

    最近在把玩AngularJS框架,之前也看过流行的Backbone,不过AngularJS给人的感觉完全不同,它走的是一条高帅富之路. 按照官方的说法,AngularJS是一套依赖注入的MVC开发套件 ...

  7. Linux Tweak:交换 Caps_Lock 与 Control_R

    很少使用的Caps_Lok键占据着键盘的黄金位置,不仅如此,它还经常被按错. 于是受到程序员神器HHKB启发(如图) 对于我,Linux程序员 + vimer来说: ESC取代`键,极大的方便了VIM ...

  8. 简单实现android和wp聊天

    使用Beetle.NetPackage简单实现android和wp聊天 Beetle.NetPackage是一个多台平开源Client TCP通讯组件,它针对不同平台提供统一的消息描述规则和使用规范可 ...

  9. ASP.NET Web API框架揭秘:路由系统的几个核心类型

    ASP.NET Web API框架揭秘:路由系统的几个核心类型 虽然ASP.NET Web API框架采用与ASP.NET MVC框架类似的管道式设计,但是ASP.NET Web API管道的核心部分 ...

  10. python实现基于CGI的Web应用

    python实现基于CGI的Web应用 本文用一个“网上书店”的web应用示例,简要介绍如何用Python实现基于CGI标准的Web应用,介绍python的cgi模块.cigtb模块对编写CGI脚本提 ...