Angular Cookies.remove not working

时间:2015-08-12 12:20:49

标签: javascript angularjs cookies

我有一个场景,我正在使用普通的java脚本添加cookie并尝试使用角度Cookie服务检索它,该服务工作正常。但是使用Cookies服务删除cookie是行不通的。我的JS就像

<script type="text/javascript">
        var app = angular.module('MyApp', ['ngCookies']);
        app.controller('MyController', function ($scope, $window, $cookies) {
            $scope.ReadCookie = function () {
                $window.alert($cookies.get('username'));
            };
            $scope.RemoveCookie = function () {
                $cookies.remove('username');
            };

        });
         function addCookie(){
                document.cookie="username=John Doe;path=/";
            }
    </script>

我的HTML

<div ng-app="MyApp" ng-controller="MyController">
        <input type="button" value="Write Cookie" onclick="addCookie()"/>
        <input type="button" value="Read Cookie" ng-click="ReadCookie()" />
        <input type="button" value="Remove Cookie" ng-click="RemoveCookie()" />
    </div>

它是否与cookie的路径有关,如果是,我怎么能在remove函数中提到路径?

4 个答案:

答案 0 :(得分:22)

尝试使用{ path: YOUR_PATH }作为参数。

例如,使用<base href="/">, 放$cookies.remove('username', { path: '/' });

答案 1 :(得分:3)

试试这个

app.controller('MyController', function ($scope, $window, $cookies) {
    $scope.ReadCookie = function () {
        $window.alert($cookies.get('username'));
    };
    $scope.RemoveCookie = function () {
        $cookies.remove('username');
    };
    $scope.addCookie= function () {
        $cookies.put('username','John',[path:'/']);
    };

});

答案 2 :(得分:0)

设置默认路径对我有用:

$cookiesProvider.defaults.path = "/";

答案 3 :(得分:0)

为了阻止我从另一个path中删除Cookie,我已经完成的诀窍是将expire日期从Cookie设置为now }¯_(ツ)_ /¯:

$cookies.put(cookieName, cookieValue, { expires: $window.moment().toString() });