1

With 1.4 version of AngularJS, is it possible to create persistent cookies with $cookies?

I want data to be stored once I login, for 7 days say. In version 1.3.X, it is not possible to set Expiration date even. But with 1.4, they have deprecated $cookieStore and set an option in $cookies for expiration date.

I want to know whether this one creates cookies for desired longer periods rather than I close the browser and everything is gone.

usingla
  • 23
  • 7
  • Related: http://stackoverflow.com/questions/24702432/angularjs-cookies-are-not-persisting – jdphenix May 26 '15 at 13:23
  • Do you really want to use cookies? Unless you need this info on every http request, I think local storage is a better option. A nice library is [here](https://github.com/grevory/angular-local-storage) and it works with 1.4 – JMK May 26 '15 at 13:44
  • You can not set the expiration date using localStorage. – Wédney Yuri May 26 '15 at 13:47
  • I think document.cookie is working – usingla May 27 '15 at 06:11

2 Answers2

2

You can set the expires property on the $cookiesProvider to change the default behaviour of the $cookies service. $cookiesProvider is available with version 1.4. For more info, see here.

Donal
  • 31,121
  • 10
  • 63
  • 72
  • I think $cookiesProvider is available in 1.3.X also. Now, Suppose I logged in and it creates a cookie with expires set to 7 days +current time. If I shut down my browser and start again, will it be there? OR is it like, maximum period of cookie is 7 days and if you shut down it ll be deleted OR if you are logged in, it ll stay for max 7 days? – usingla May 27 '15 at 06:11
0

The code below do what you want. When you are writing the cookie you can tell the expiration date. You can close the browser and the cookie will remain active.

Setting expiry dates PREVENT it from being deleted when the browser is closed. setting persistent cookies with javascript

<!DOCTYPE html>
<html ng-app="cookiesExample">

  <head>
    <meta charset="utf-8" />
    <script src="https://code.angularjs.org/1.4.0-rc.2/angular.js"></script>
    <script src="https://code.angularjs.org/1.4.0-rc.2/angular-cookies.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <script>
        angular.module('cookiesExample', ['ngCookies'])
      .controller('MainCtrl', ['$cookies', '$scope', function($cookies, $scope) {
        // Retrieving a cookie
        var favoriteCookie = $cookies.get('myFavorite');

        $scope.name = (favoriteCookie) ? 'welcome back' : 'first time';
        // Setting a cookie

        var now = new Date();
        now.setDate(now.getDate() + 7);
        $cookies.put('myFavorite', 'oatmeal', {
          expires: now
        });

      }]);
    </script>
  </body>


</html>
Community
  • 1
  • 1
Wédney Yuri
  • 1,267
  • 12
  • 21