$ cookie with angularjs 1.4 expiration date

How to set an expiration cookie with angularjs 1.4. The documentation says that

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 only shows the expiration date as a session.

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 installing jsFiddle, but I could not save it. My warning displays undefined.

+5
source share
3 answers

Turn on your problem by debugging something like this.

The main error was caused by 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 - related in the sidebar - I am connected with 1.4.2 on google cdn.

+6
source

Use this modified angular-cookies library. In this case, you can set cookies with the expires and path object skipped as well

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

Example:

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

Set the hours, minutes, days of the date to set the expiration of cookies. by default there will be a session.

(sorry for the bad english :)

+3
source

I ran into this problem when firefox did not save cookies. According to the document https://docs.angularjs.org/api/ngCookies/service/ $, the correct cookie should be:

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

Note: "expires vs expiry and [] wrapping args.

+2
source

All Articles