robin
robin

Reputation: 1925

Angular Cookies.remove not working

I have a scenario where I am adding a cookie using normal java-script and trying to retrieve it using angular Cookies service which is working fine. But the removal of the cookie using Cookies service is not working. My JS is like

<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>

My HTML is

<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>

Is it related to the path of the cookie, if yes how can i mention the path in the remove function ?

Upvotes: 12

Views: 14247

Answers (4)

Marlon Barcarol
Marlon Barcarol

Reputation: 508

In order to the angular blocking me to delete the cookie from another path the trick that I have done to work-around it was to set the expire date from the cookie to now ¯_(ツ)_/¯ :

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

Upvotes: 0

Amir Savand
Amir Savand

Reputation: 384

Setting default path worked for me:

$cookiesProvider.defaults.path = "/";

Upvotes: 0

user5507803
user5507803

Reputation:

Try with { path: YOUR_PATH } as parameter.

For example, with <base href="/">, put $cookies.remove('username', { path: '/' });

Upvotes: 29

Vishnu
Vishnu

Reputation: 12293

Try this

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:'/']);
    };

});

Upvotes: 5

Related Questions