AngularJS $ Cookie不会持续 [英] AngularJS $cookies are not persisting
问题描述
我有一个记住用户功能的登录表单。他们做的是检查框和饼干是通过保存:
I have a login form with a remember username function. All they do is check the box and the cookie is saved via:
$scope.toggleCookie = function()
{
//-- $scope.remember is the model for the checkbox
$cookieStore.put('remember', $scope.remember);
if (!$scope.remember) $cookieStore.remove('email');
}
当用户返回到登录页面,首先我检查记住
的cookie:
When the user returns to the login page, first I check the remember
cookie:
$scope.remember = ($cookieStore.get('remember') == null || $cookieStore.get('remember') == false) ? false : true;
然后我检查是否有在电子邮件值
的cookie:
$scope.email = ($cookieStore.get('email') != null) ? $cookieStore.get('email') : '';
现在所有上述工作正常,我可以登录它检查,注销,我可以看到我的用户名输入字段中。如果我取消它,登录和注销,用户名消失了。
Now all the above is working fine, I can login with it checked, logout and I can see my username in the input field. If I uncheck it, login and logout, the username is gone.
我也能看到这种情况发生在资源 - >饼干标签在Chrome开发工具。
I can also see this happening in the resources->cookies tab in the chrome dev tools.
我可以刷新页面,不过,用户名是有检查的时候。
I can refresh the page and still, the username is there when checked.
我的问题的是,当我关闭铬,重新打开它,所有的Cookie数据已经一去不复返了。为什么是这样?我没有与饼干太多的经验开始。
My issue is that when I CLOSE chrome, reopen it, all the cookie data is gone. Why is this? I don't have much experience with cookies to begin with.
推荐答案
在角V1.4可以的最后设置一些用于饼干选项。这里是一个非常简单的例子:
In Angular v1.4 you can finally set some options for the cookies. Here's a very simple example:
var now = new $window.Date(),
// this will set the expiration to 6 months
exp = new $window.Date(now.getFullYear(), now.getMonth()+6, now.getDate());
$cookies.put('yourCookie','blabla',{
expires: exp
});
var cookie = $cookies.get('yourCookie');
console.log(cookie); // logs 'blabla'
如果您在运行此code之后检查你的cookies,你会看到,过期将被正确设置为名为 yourCookie
。
If you check your cookies after running this code you will see that the expiration will be properly set to the cookie named yourCookie
.
作为第三个参数的把
上面的函数传递的对象允许其他选择,如设置路径
,域
和安全
。检查的文档的概述。
The object passed as a third param to the put
function above allows for other options as well, such as setting path
, domain
and secure
. Check the docs for an overview.
这篇关于AngularJS $ Cookie不会持续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!