我有一个带有记住用户名功能的登录表单。他们所做的只是选中复选框,然后通过以下方式保存 cookie:
$scope.toggleCookie = function()
{
//-- $scope.remember is the model for the checkbox
$cookieStore.put('remember', $scope.remember);
if (!$scope.remember) $cookieStore.remove('email');
}
当用户返回登录页面时,我首先检查remember
cookie:
$scope.remember = ($cookieStore.get('remember') == null || $cookieStore.get('remember') == false) ? false : true;
然后我检查 email
cookie 中是否有值:
$scope.email = ($cookieStore.get('email') != null) ? $cookieStore.get('email') : '';
现在以上所有工作正常,我可以登录并注销,我可以在输入字段中看到我的用户名。如果我取消选中它,登录并注销,用户名就会消失。
我还可以在 chrome 开发工具的资源->cookie 选项卡中看到这种情况。
我可以刷新页面,用户名仍然存在。
我的问题 是当我关闭 chrome 并重新打开它时,所有 cookie 数据都消失了。为什么是这样?我一开始对 cookie 没有太多经验。
最佳答案
在 Angular v1.4 中,您终于可以为 cookie 设置一些选项。这是一个非常简单的例子:
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'
如果您在运行此代码后检查您的 cookie,您会看到过期时间将正确设置为名为 yourCookie
的 cookie。
作为第三个参数传递给上面的 put
函数的对象还允许其他选项,例如设置 path
、domain
和安全
。检查the docs概览。
关于javascript - AngularJS $cookies 不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24702432/