Angular JS - invalid number of domains set $ cookies

I am having trouble setting cookies in my angularjs app. The situation is that I want to set site-wide cookies, but I have no idea how to set all options for cookies using angular js default $ cookie object.

For example, normally in Javascript I would write this

var exp = new Date();
exp.setTime(exp.getTime()+(24*60*60*1000)); // expires after a day
document.cookie = "myCookies=yes;expires="+exp.toGMTString()+ ";domain=.example.com;path=/";

      

But since the DOM object cannot be easily loaded into my application, I have to use $ cookies (angular-cookies.js). New code:

angular.module('MyApp')
    .controller('MyCtrl', function ($scope, $filter, Slug,PUBLIC_ROUTES, $cookies) {
        var myCookies = $cookies['mycookies'];
        if (typeof myCookies == 'undefined' || typeof myCookies == undefined) {
            $cookies['mycookies'] = "yes";
        }
    });

      

But I cannot set the expiration date, path and domain as they are not available for the $ cookie.

What should I do?

+3


source to share


2 answers


If you are using angular 1.4+ just set $cookiesProvider.defaults

in the config section of your main app module. Example:

angular.module('my-app', [ngCookies])
.config(['$cookiesProvider', function($cookiesProvider) {
    // Set $cookies defaults
    $cookiesProvider.defaults.path = '/';
    $cookiesProvider.defaults.secure = true;
    $cookiesProvider.defaults.expires = exp_date;
    $cookiesProvider.defaults.domain = my_domain;
}]);

      

Just don't make the same mistake as me by first assigning default values ​​to a new object:



$cookiesProvider.defaults = {path: '/', secure: true};

      

This will break the object reference and the defaults will no longer be overridden.

+10


source


$, the cookies have allows put(key, value, [options])

the parameters $ cookiesProvider , including expires .



You can also take a look at How to Set a Cookie Expiration Date in AngularJS

+1


source







All Articles