本地存储 cookie,session,localstorage( 二)angular-local-storage
原文: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: localStorage, sessionStorage). 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: localStorage, sessionStorage). 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的更多相关文章
- 本地存储 cookie,session,localstorage( 一)基本概念及原生API
http://www.w3school.com.cn/html5/html_5_webstorage.asp http://adamed.iteye.com/blog/1698740 localSto ...
- jquery访问浏览器本地存储cookie,localStorage和sessionStorage
前言:cookie,localStorage和sessionStorage都是浏览器本地存储数据的地方,其用法不尽相同:总结一下基本的用法. 一.cookie 定义: 存储在本地,容量最大4k,在同源 ...
- 本地存储常用方式 localStorage, sessionStorage,cookie 的区别 和 服务器存储session
本地存储:把一些信息存储到客户端本地(主要目的有很多,其中有一个就是实现多页面之间的信息共享) 1. 离线缓存(xxx.manifest) H5处理离线缓存还是存在一些硬伤的,所以真实项 ...
- 本地存储sessionStorage 、 localStorage 、cookie整理
sessionStorage . localStorage .cookie 的区别 sessionStorage 和 localStorage 是HTML5 Web Storage API 提供的,可 ...
- H5新特性 本地存储---cookie localStorage sessionStorage
本地存储的作用 :避免登录网站时,用户在页面浏览时重复登录,也可以实现快速登录,一段时间内保存用户的登录效果,提高页面访问速率 在html5中提供三种数据持久化操作的方法: 1.cookie 可看作是 ...
- 地理位置(navigation.geolocation)与本地存储(seessionStorage、localStorage)
一.地理位置( geolocation ): navigator.geolocation对象: 1.单次请求: //navigator.geolocation.getCurrentPosition( ...
- 常用的本地存储-----cookie篇
1.引言 随着浏览器的处理能力不断增强,越来越多的网站开始考虑将数据存储在「客户端」,那么久不得不谈本地存储了. 本地存储的好处: 一是避免取回数据前页面一片空白,如果不需要最新数据也可以减少向服务器 ...
- javascript的本地存储 cookies、localStorage
一.cookies 本地存储 首先是常用的cookies方法,网上有很多相关的代码以及w3cSchool cookies. // 存储cookies function setCookie(name,v ...
- 浏览器存储(cookie、localStorage、sessionStorage)
互联网早期浏览器是没有状态维护,这个就导致一个问题就是服务器不知道浏览器的状态,无法判断是否是同一个浏览器.这样用户登录.购物车功能都无法实现,Lou Montulli在1994年引入到web中最终纳 ...
随机推荐
- 解决nexus下载maven索引的问题
解决nexus下载maven索引的问题 (2011-10-12 17:48:46) 转载▼ 标签: it 分类: java 转自 http://www.colorfuldays.org/program ...
- 基于Jquery 简单实用的弹出提示框
基于Jquery 简单实用的弹出提示框 引言: 原生的 alert 样子看起来很粗暴,网上也有一大堆相关的插件,但是基本上都是大而全,仅仅几句话可以实现的东西,可能要引入好几十k的文件,所以话了点时间 ...
- Webapi备忘-20140109
r01的翻译系列:http://www.cnblogs.com/r01cn/category/428069.html 接收FROM数据 Webapi接收表单数据,如果有多个数据比如x=1&y= ...
- MD5算法-爬虫学习(五)
在实现爬虫的时候,我们使用Hash结构去存储我们用过的URL的时候,有些URL可能长度很长,为了更加节省空间,我们就要对URL进行压缩,帮它减减肥,这个我们介绍这个MD5算法,可以对URL进行有效的压 ...
- c#多选下拉框(ComboBox)
代码如下 using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawi ...
- C#socket通信1
.net平台下C#socket通信(上) 完全是基础,新手可以随意看看,大牛可以关闭浏览页了,哈哈. 在开始介绍socket前先补充补充基础知识,在此基础上理解网络通信才会顺理成章,当然有基础的可以跳 ...
- springmvc国际化 基于请求的国际化配置
springmvc国际化 基于请求的国际化配置 基于请求的国际化配置是指,在当前请求内,国际化配置生效,否则自动以浏览器为主. 项目结构图: 说明:properties文件中为国际化资源文件.格式相关 ...
- svn签出单个文件
) { return new string[]{ string.Format("cd /d \"{0}\"",System.IO.Path.GetDirecto ...
- IE8下提示'console'未定义错误
在开发的过程中由于调试的原因,在代码中加入console.info("xxxx"),而未进行删除 在IE8下测试该代码所在的页面报错,如下: 需要注意的是,使用console对象查 ...
- asp.net做的网站账号登陆后注销不管用了
最近做了个项目用到了数据库登录,A登陆后把登录状态保,个人信息存在Session里,但是奇怪的是,只要有一个用户登录后在其他电脑上打开上述页面,则也显示A登录状态,注销也不管用了.以前还号的.求大神啊 ...