angular1.4及以上版本才支持$cookies。
项目引入的是1.4.2版本,操作cookies原先一直用的是$cookieStore,用的飞起啊。
$cookieStore.remove("user"); //检测是否存在cookie user $scope.pass = $cookieStore.get("pass"); //记录登录时间 $scope.loginTime = new Date().getTime(); $cookieStore.put("loginTime", $scope.loginTime); var cookieDate = {}; cookieDate.sid = data.con.sid; cookieDate.uid = data.con.uid; cookieDate.tid = data.con.tid; cookieDate.token = data.con.token; cookieDate.email = data.con.email; $cookieStore.put("user", cookieDate); if ($scope.isRemember) { var expireDate = new Date(); expireDate.setDate(expireDate.getDate() + 30);//设置cookie保存30天 $cookieStore.put("pass", {'email':$scope.email, 'password':$scope.password}, {'expires': expireDate}); } else { $cookieStore.remove("pass"); }
后来发现了一个严重的问题。在群里发现有人问问题,用的1.2版本的angular-cookie,$cookieStore设置保存时间没用。我一想,这怎么可能,嗤之以鼻。后来那人多次询问,我就把我的代码贴给他看了。也没什么,我就闭群看文章了。中途打野,想试试cookie怎么弄,毕竟自己也没弄多大明白,就换了个不常用的浏览器试了试。握草,cookie的设置根本没用啊!!于是查阅了些资料,好像cookieStore不支持保存的时间期限。
$cookies.putObject(key,value,[options]);
$cookieStore.put(key,value);
这就是差别!于是瞬间全部换成$cookies写法。而且人老外也说了,以后会逐步摒弃$cookieStore,而更多使用$cookies。
$cookies.remove("user"); //检测是否存在cookie user $scope.pass = $cookies.getObject("pass"); //记录登录时间 $scope.loginTime = new Date().getTime(); $cookies.put("loginTime", $scope.loginTime); var cookieDate = {}; cookieDate.sid = data.con.sid; cookieDate.uid = data.con.uid; cookieDate.tid = data.con.tid; cookieDate.token = data.con.token; cookieDate.email = data.con.email; $cookies.putObject("user", cookieDate); if ($scope.isRemember) { var expireDate = new Date(); expireDate.setDate(expireDate.getDate() + 30);//设置cookie保存30天 $cookies.putObject("pass", {'email': $scope.email, 'password': $scope.password}, {'expires': expireDate}); } else { $cookies.remove("pass"); }
在其他控制器获取cookie内容也很简单:
$scope.ID = $cookies.getObject("user").email; $scope.sid = $cookies.getObject("user").sid; $scope.uid = $cookies.getObject("user").uid; $scope.token = $cookies.getObject("user").token;
另外有的浏览器有自动填充账号密码功能(导致我以为我的cookie设置好了),可以在设置里面查看cookie是否保存成功。