How to set expiration date for cookie in AngularJS

Anand picture Anand · Sep 27, 2012 · Viewed 98.7k times · Source
  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.

Answer

Geert van Dort picture Geert van Dort · Mar 13, 2015

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