12

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 ?

robin
  • 1,893
  • 1
  • 18
  • 38
  • You should use angular way of creating a new cookie. also check do you have in you html. – vaske Aug 12 '15 at 12:33

4 Answers4

29

Try with { path: YOUR_PATH } as parameter.

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

4

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

});
Vishnu
  • 11,614
  • 6
  • 51
  • 90
  • Actually I cannot add a cookie using angular. Its an existing scenario done by a servlet. All i need is the removal of the cookie. – robin Aug 12 '15 at 12:50
  • http://stackoverflow.com/questions/14196229/cant-delete-cookie-with-angularjss-cookies – Vishnu Aug 12 '15 at 12:53
0

Setting default path worked for me:

$cookiesProvider.defaults.path = "/";
Amir Savand
  • 365
  • 5
  • 13
0

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() });
Marlon Barcarol
  • 508
  • 5
  • 12