本地存储 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中最终纳 ...
随机推荐
- android 布局属性大全---初学者必备
Android功能强大,界面华丽,但是众多的布局属性就害苦了开发者,下面这篇文章结合了网上不少资料,花费本人一个下午搞出来的,希望对其他人有用. 第一类:属性值为true或false android: ...
- div高度自适外层div高度随里层div高度自适
尝试过许多办法 其中一网友的最靠谱就是在外层div样式添加两个标签(不能少) clear:both; overflow:auto;
- Java 8新特性前瞻
快端午小长假了,要上线的项目差不多完结了,终于有时间可以坐下来写篇博客了. 这是篇对我看到的java 8新特性的一些总结,也是自己学习过程的总结. 几乎可以说java 8是目前为止,自2004年jav ...
- JavaScript实例技巧精选(12)—计算星座与属相
>>点击这里下载完整html源码<< 这是截图: 核心代码如下: <SCRIPT LANGUAGE="JavaScript"> <!-- ...
- 由于检索用户的本地应用程序数据路径时出错,导致无法生成 SQL Server 的用户实例
/”应用程序中的服务器错误. 由于检索用户的本地应用程序数据路径时出错,导致无法生成 SQL Server 的用户实例.请确保该用户在此计算机上有本地用户配置文件.该连接将关闭. 堆栈跟踪: [Sql ...
- MVC使用RDL报表
MVC使用RDL报表 这次我们来演示MVC3怎么显示RDL报表,坑爹的微软把MVC升级到5都木有良好的支持报表,让MVC在某些领域趋于短板 我们只能通过一些方式来使用rdl报表. Razor视图不支持 ...
- Java字符串转换为日期和时间比较大小
字符串转换为时间: String data = "2014/7/11"; SimpleDateFormat dfs = new SimpleDateFormat("yyy ...
- JavaScript修改Canvas图片
用JavaScript修改Canvas图片的分辨率(DPI) 应用场景: 仓库每次发货需要打印标签, Canvas根据从数据库读取的产品信息可以生成标签JPG, 但是这个JPG图片的默认分辨率(D ...
- C/C++基础知识总结——数组、指针域、字符串
1. 数组 1.1 数组作为函数参数 (1) 如果使用数组作为函数的参数,则实参和形参都是数组名,且类型要相同.数组名做参数时传递的是地址 (2) 使用方法: void rowSum(int a[][ ...
- js闭包(转)
一.变量的作用域 要理解闭包,首先必须理解Javascript特殊的变量作用域. 变量的作用域无非就是两种:全局变量和局部变量. Javascript语言的特殊之处,就在于函数内部可以直接读取全局变量 ...