1

In my application I am using angularJS 1.3, when I using $cookies to store some values I need to set 1 min expiration time of cookie. The angularJs 1.3 $cookies service has not put method to supply expiration time. this is the code I tried so far.

var x = new Date();
x.setMinutes(x.getMinutes() + 1);

$cookies['showStartUpScreen'] = value + ';expires=' + x.toGMTString();
Azad
  • 5,144
  • 4
  • 28
  • 56

1 Answers1

1

The ability to set expiration time for cookies was added in 1.4, along with an overhaul of how Angular works with cookies generally. In 1.3 however, you could use plain JS to set the cookie with expiration, as Angular polls for cookie changes.

  var date = new Date();
  var expireTime = date.getTime() + 5000 // 5 seconds
  date.setTime(expireTime);
  console.log(date)
  document.cookie = 'myFavorite=ok;expires='+date.toGMTString()+';path=/';

  // Retrieve cookie using both vanilla and Angular
  console.log(document.cookie)
  var theCookie = $cookies.myFavorite
  console.log(theCookie)

I've set up a proof of concept on CodePen, with a button you can press after 5 seconds to show the cookie does expire as expected.

References:

Community
  • 1
  • 1
  • 1
    As an addendum to this, I sincerely recommend upgrading to a more recent version of AngularJS if you can. As well as the new cookie functionality, things like setting up controllers or directives has been simplified greatly and there are many performance improvements. – Colin Tindle Mar 30 '17 at 09:49