原文: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. Andy Williams 《Love Story》

    where do i beginto tell a story of how great a love can bethe sweet love story that is older than th ...

  2. 64位平台支持大于2 GB大小的数组

    64位平台支持大于2 GB大小的数组 64位平台.NET Framework数组限制不能超过2GB大小.这种限制对于需要使用到大型矩阵和向量计算的工作人员来说,是一个非常大问题. 无论RAM容量有多大 ...

  3. hibernate配置jndi

    tomcat里的conf->context.xml <Resource name="mysql"     auth="Container" type ...

  4. Bootstrap导航悬浮顶部,stickUp

    stickUp 一个 jQuery 插件 这是一个简单的jQuery插件,它能让页面目标元素 “固定” 在浏览器窗口的顶部,即便页面在滚动,目标元素仍然能出现在设定的位置.此插件可以在多页面的网站上工 ...

  5. Binder机制,从Java到C (1. IPC in Application Remote Service)

    转载请标注:张小燕:http://www.cnblogs.com/zhangxinyan 1. Application 中的 service 我们知道Android中Service有三种类型:Loca ...

  6. Binder机制,从Java到C (5. IBinder对象传递形式)

    1.IBinder的传递 Binder IPC通信中,Binder是通信的媒介,Parcel是通信的內容.远程调用过程中,其参数都被打包成Parcel的形式來传递.IBinder对象当然也不例外,在前 ...

  7. Dirichlet's Theorem on Arithmetic Progression

    poj3006 Dirichlet's Theorem on Arithmetic Progressions 很显然这是一题有关于素数的题目. 注意数据的范围,爆搜超时无误. 这里要用到筛选法求素数. ...

  8. SET IDENTITY_INSERT详解

    声明:本博文摘自http://www.lmwlove.com/ac/ID500 自增列默认是不能插入显式值的,当我们试图给自增列插入值时,会报以下错误:当 IDENTITY_INSERT 设置为 OF ...

  9. Asycn/Await 异步编程

    Asycn/Await 异步编程初窥(二)   经过总过4天的学习和实践,做完了 WinForm 下 .Net 4.5 的基本异步应用,实现了一个 Http 协议下载的测试程序,为以后使用 .Net ...

  10. jQuery Validation让验证变得如此容易(二)

    上一个例子我们是统一引用jquery.validate.js这样所有必填字段的提示信息都将是This field is required. 现在要改成动态提示,比如姓名如果为空则提示姓名不能为空,密码 ...