AngularJS $ cookies不会持久存在

Ron*_*nie 14 javascript cookies angularjs

我有一个记住用户名功能的登录表单.他们所做的只是勾选方框,并通过以下方式保存cookie:

$scope.toggleCookie = function()
{
    //-- $scope.remember is the model for the checkbox
    $cookieStore.put('remember', $scope.remember);
    if (!$scope.remember) $cookieStore.remove('email');
}
Run Code Online (Sandbox Code Playgroud)

当用户返回登录页面时,首先检查remembercookie:

$scope.remember = ($cookieStore.get('remember') == null || $cookieStore.get('remember') == false) ? false : true;
Run Code Online (Sandbox Code Playgroud)

然后我检查emailcookie中是否有值:

$scope.email = ($cookieStore.get('email') != null) ? $cookieStore.get('email') : '';
Run Code Online (Sandbox Code Playgroud)

现在以上所有工作正常,我可以登录检查,注销,我可以在输入字段中看到我的用户名.如果我取消选中它,登录并注销,用户名就会消失.

我也可以在chrome dev工具的resources-> cookies选项卡中看到这种情况.

我可以刷新页面,但是,当检查时,用户名就在那里.

我的问题是当我关闭chrome时,重新打开它,所有的cookie数据都消失了.为什么是这样?我没有太多使用cookies的经验.

Nob*_*ita 21

在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'
Run Code Online (Sandbox Code Playgroud)

如果您在运行此代码后检查您的cookie,您将看到过期将正确设置为名为的cookie yourCookie.

作为第三PARAM到传递的对象put上述功能允许其他选项,以及,诸如设置path,domainsecure.查看文档以获取概述.