How to set expiration date for cookie in AngularJS

  1. We want to store User's Authorization information in cookie which should not be lost upon refresh (F5) of browser.

  2. We want to store authorization info in "permanent-cookie" in case user has opted for "Remember Me" check box at the time of log-on.

103376 次浏览

As @vincent-briglia pointed out, there's a jQuery drop-in that can be used as a workaround until $cookie service becomes configurable - check it out here

For 1.4: As noted in the comment here and others below, as of 1.4, Angular's native cookie support now provides the ability to edit cookies:

Due to 38fbe3ee, $cookies will no longer expose properties that represent the current browser cookie values. $cookies no longer polls the browser for changes to the cookies and no longer copies cookie values onto the $cookies object.

This was changed because the polling is expensive and caused issues with the $cookies properties not synchronizing correctly with the actual browser cookie values (The reason the polling was originally added was to allow communication between different tabs, but there are better ways to do this today, for example localStorage.)

The new API on $cookies is as follows:

get put getObject putObject getAll remove You must explictly use the methods above in order to access cookie data. This also means that you can no longer watch the properties on $cookies to detect changes that occur on the browsers cookies.

This feature is generally only needed if a 3rd party library was programmatically changing the cookies at runtime. If you rely on this then you must either write code that can react to the 3rd party library making the changes to cookies or implement your own polling mechanism.

The actual implementation is done via a $cookiesProvider object, which can be passed via the put call.

For 1.3 and below: For those of you who have done your best to avoid having to load jQuery plugins, this appears to be a nice replacement for angular - https://github.com/ivpusic/angular-cookie

You can go to the angular.js script and change the insert cookie
search for self.cookies = function(name, value) { then u can change the code that adds the cookie for example for 7 days

 if (value === undefined) {
rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
";expires=Thu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
var now = new Date();
var time = now.getTime();
time += 24*60*60*1000*7;
now.setTime(time);
cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
';path=' + cookiePath+";expires="+now.toGMTString()).length + 1

I know that this question is a little bit old, and already have an accepted answer.

But still a present problem which I 'm struggling with (not regarding jQuery or pure Javascript).

So, after some research I have found this: https://github.com/ivpusic/angular-cookie

Which delivers an "interface" quite similar to $cookieStore. And permits to configure the expiration date (value and units).

About angular native support on the expiration date with $cookie or $cookieStore, "they" promise updates on this subject on 1.4, look into this: https://github.com/angular/angular.js/pull/10530

It will be possible to set expiration date with $cookieStore.put(...), at least they propose that...

EDIT: I encountered a "problem" you cannot mix $cookies with angular-cookie modular. So if you set a cookie withipCookie(...) retrieve it with ipCookie(...) because with $cookie it will return undefined.

In Angular v1.4 you can finally set some options for the cookies, such as the expiration. Here's a very simple example:

var now = new Date(),
// this will set the expiration to 12 months
exp = new Date(now.getFullYear()+1, now.getMonth(), now.getDate());


$cookies.put('someToken','blabla',{
expires: exp
});


var cookie = $cookies.get('someToken');
console.log(cookie); // logs 'blabla'

If you check your cookies after running this code you will see that the expiration will be properly set to the cookie named someToken.

The object passed as a third param to the put function above allows for other options as well, such as setting path, domain and secure. Check the docs for an overview.

PS - As a side note if you are upgrading mind that $cookieStore has been deprecated, so $cookies is now the only method to deal with cookies. see docs

This is possible in the 1.4.0 build of angular using the ngCookies module:

https://docs.angularjs.org/api/ngCookies/service/$cookies

angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Find tomorrow's date.
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() + 1);
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal', {'expires': expireDate});
}]);

I would like to present an extra example as some people know the extra duration of the cookies lifetime. ie. They want to set a cookie to last 10 more minutes, or 1 more day.

Usually you already know how much longer the cookie will last in seconds.

    var today = new Date();
var expiresValue = new Date(today);


//Set 'expires' option in 1 minute
expiresValue.setMinutes(today.getMinutes() + 1);


//Set 'expires' option in 2 hours
expiresValue.setMinutes(today.getMinutes() + 120);




//Set 'expires' option in (60 x 60) seconds = 1 hour
expiresValue.setSeconds(today.getSeconds() + 3600);


//Set 'expires' option in (12 x 60 x 60) = 43200 seconds = 12 hours
expiresValue.setSeconds(today.getSeconds() + 43200);


$cookies.putObject('myCookiesName', 'myCookiesValue',  {'expires' : expiresValue});

and you can retrieve it as usual:

    var myCookiesValue = $cookies.getObject('myCookiesName');

If empty, it returns undefined.

Links;

http://www.w3schools.com/jsref/jsref_obj_date.asp
https://docs.angularjs.org/api/ngCookies/provider/$cookiesProvider#defaults

You may use https://github.com/ivpusic/angular-cookie

First you need to inject ipCookie into your angular module.

var myApp = angular.module('myApp', ['ipCookie']);

And now, for example if you want to use it from your controller

myApp.controller('cookieController', ['$scope', 'ipCookie', function($scope, ipCookie) {
// your code here
}]);

To create a cookie use

ipCookie(key, value);

The value supports strings, numbers, booleans, arrays and objects and will be automatically serialized into the cookie.

You can also set some additional options, like number of day when a cookie expires

ipCookie(key, value, { expires: 21 });