javascript - AngularJS $cookies 不持久

标签 javascript angularjs cookies

我有一个带有记住用户名功能的登录表单。他们所做的只是选中复选框,然后通过以下方式保存 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 函数的对象还允许其他选项,例如设置 pathdomain安全。检查the docs概览。

关于javascript - AngularJS $cookies 不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24702432/

相关文章:

javascript - 如何使用 POST 提交

javascript - 结合 ng repeat 和 django 模板语言

javascript - 在 AngularJS 中,为什么终端自定义指令的行为会随着内置指令而改变?

javascript - 仅显示 div(预加载器)一次 - 直到清除缓存/ session

javascript - String.Replace() 的小问题

javascript - 如何命名 es6 类(针对 React 组件)

javascript - 如何访问本地明文js文件并保存为变量

javascript - 优先考虑 jQuery 在脚本之前

ruby - 我如何使用 Sinatra 读取 cookie?

javascript - Chrome 扩展 cookies.getAll 不起作用