Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$cookies with angularjs 1.4 expiration date

How do i set the cookie with expiration date with angularjs 1.4. The documentation says to use

expires - {string|Date} - String of the form "Wdy, DD Mon YYYY HH:MM:SS GMT" or a Date object indicating the exact date/time this cookie will expire.

But its not working.My firebug is showing the expiration date as Session only.

HTML

<div ng-app="cookieApp" ng-controller="cookieCtrl">
    <button ng-click="setCookie()">Set Cookie</button>
     <button ng-click="getCookie()">Get Cookie</button>
</div>

Javascript

    var app=angular.module("cookieApp",['ngCookies']);
app.controller("cookieCtrl",function($scope, $cookies){
    $scope.setCookie = function(){
    console.log("setCookie");
        var now = new Date();
        now.setDate(now.getDate() + 7);
          $cookies.put("tech","angularjs",{expiry:now});
     }
     $scope.getCookie = function(){
          alert( $cookies.get("tech"));
    }
});

I tried to set the jsFiddle but i couldnt save it. My alert is showing undefined.

like image 877
Alaksandar Jesus Gene Avatar asked Aug 11 '15 06:08

Alaksandar Jesus Gene


3 Answers

Ran into your problem debugging something similar.

The main bug was due to expiry vs expires in your code.

var app = angular.module("cookieApp", ["ngCookies"]);
app.controller("cookieCtrl", function ($scope, $cookies) {
    $scope.setCookie = function () {
        console.log("setCookie");

        var now = new Date();
        now.setDate(now.getDate() + 7);

        $cookies.put("tech", "angularjs", {
            expires: now
        });
    }
    $scope.getCookie = function () {
        alert($cookies.get("tech"));
    }
});

jsfiddle: http://jsfiddle.net/ucskyv67/

Note the two dependencies on angular.js and angular-cookies.js - linked in the side bar - I've linked to 1.4.2 on google's cdn.

like image 151
Ali W Avatar answered Oct 08 '22 23:10

Ali W


Use this one modified library of angular-cookies. In this you can set cookies with passing object of expires and path also

https://github.com/babarxm/angular-cookies-fixed/tree/v1.5.6

Example:

$cookies.put("token", {
    expires : new Date(),
    path : "/somepath"
});

Set the hours, mins, days of date object to set cookies expiring. default will be session.

(sorry for bad english :)

like image 32
Babar Bilal Avatar answered Oct 08 '22 23:10

Babar Bilal


I have run into this issue with firefox not saving cookies. According to the doc https://docs.angularjs.org/api/ngCookies/service/$cookies, the correct cookie call should be :

$cookies.put("tech","angularjs",[{expires:now}]);

note the "expires vs expiry and the [] wrapping args.

like image 40
user3886397 Avatar answered Oct 09 '22 00:10

user3886397