AngularJS中对cookie的操作封装了一个单独的模块,模块名为ngCookies,若想使用需在页面中先引入angular-cookies.js:
<script src="https://www.jb51.net/js/angular.min.js"></script> <script src="https://www.jb51.net/js/angular-cookies.js"></script>
然后將ngCookies模块注入到我们自定义的模块的依赖模块中:
var app = angular.module("myApp",['ngCookies']);
ngCookies模块中有两个cookies读写相关的服务:$cookies和$cookieStroe。无论使用哪种都要先将其注入到控制器中,为了比较二者的区别,都将其注入到控制器中:
app.controller('namesCtrl', ['$cookies','$cookieStore',function($cookies, $cookieStore){}]);
设置cookie用put()方法:
$cookies.put(key, value[, options]);
$cookieStore.put(key, value);
例如设置一个cookie,名为“userName”,值为“yangmin”:
//使用$cookies设置cookie $cookies.put('userName', 'yangmin');
//使用$cookieStore设置cookie $cookieStore.put('userName','yangmin');
获取cookie用get()方法:
$cookies.get(key);
$cookieStore.get(key);
例如获取上面设置的“userName”:
$cookies.get(userName);//yangmin
$cookieStore.get("userName"); //yangmin
删除cookie用remove():
$cookies.remove(key[, options]);
$cookieStore.remove(key);
例如删除“userName”
$cookies.remove("userName");
$cookieStore.remove("userName");
$cookies和$cookieStore的区别:
1.$cookies设置的cookie值一般为字符串,$cookieStroe可用于设置字符串、对象、数组等。
$cookies.put("person",{name:"Amy",age:23}); var person = $cookies.get("person"); console.log(person.age);//undefined
$cookieStore.put("person",{name:"Amy",age:23}); var person = $cookieStore.get("person"); console.log(person.age);//23
2.$cookies可设置参数,例如可设置cookie的过期时间。$cookieStore无法设置参数
var expireDate = new Date(); expireDate.setDate(expireDate.getDate() + 1); $cookies.put("userName",“yangmin”,{'expires': expireDate});//“userName”一天后过期