AngularJS and Cookies

AngularJS has built in support for cookies. A cookie may be added by simply injecting $cookies into your service or controller and creating a cookie by:

$cookies.MyToken = value;

The value can then also be read from the cookies easily by:

var myToken = $cookies.MyToken;

This obviously is a nice feature which abstracts away much of the javascript usually written for creating and reading cookies.

The problem with the current way angular cookies are created is that all cookies by default are set to expire at the end of the browsing session and as of this post there isn’t a way to change that. The problem has been recognized and the creators of angular are working on allowing expiration to be set on cookies in a future update. For the time being we have stopped using $cookies and are using some simple javascript to create cookies but then use angular to read and delete cookies.

Here is some javascript on how to create a new cookie with an expiration of 30 days:

var expirationDate = new Date();
var myValue;

expirationDate.setDate(expirationDate.getDate() + 30);
document.cookie = "MyToken" + "=" + myValue + "; expires=" + expirationDate.toUTCString();

In order to delete an angular cookie simply use:

delete $cookies["MyToken"];

1 reply
  1. Ty Seddon
    Ty Seddon says:

    Handy function to delete all cookies

    function deleteAllCookies() {
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i]; var eqPos = cookie.indexOf("="); var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
    }

Comments are closed.