Artvader
Artvader

Reputation: 958

How to store (and retrieve) a cookie array with Angular cookies

I'm trying to store my cookies with AngularJS as an array to keep the cookie file clean.

I'm using the following method:

$cookies.put('myCookieArray',{'key1':'value1','key2':'value2'});

Now, when I try to retrieve it using:

getmycookiesback = $cookies.get('myCookieArray');
console.log(getmycookiesback.key1);

I get an undefined value.

but when I try to retrieve it using this:

console.log($rootScope.getmycookiesback);

It retrieves [object Object].

What am I doing wrong? I want to get the value from key1 and key2.

Upvotes: 9

Views: 6024

Answers (2)

thegio
thegio

Reputation: 1243

try like that:

 DemoApp.controller('DemoController', function ($cookies, $scope, $log) {

            //$cookies.put('myCookieArray',{'key1':'value1','key2':'value2'});
            $cookies['myCookieArray']= {'key1':'value1','key2':'value2'};

            getmycookiesback = $cookies['myCookieArray'];
            $log.info(getmycookiesback.key1);  
        })

here the plunker: http://plnkr.co/edit/k9fltjGUbTbfbVlAmRcJ

I hope it helps

Upvotes: 3

strelok2010
strelok2010

Reputation: 1266

Use $cookies.putObject('myCookieArray',{'key1':'value1','key2':'value2'}); and getmycookiesback = $cookies.getObject('myCookieArray');

Upvotes: 6

Related Questions