Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs cookies - How to use them across controllers

There doesn't seem to be any really clear documentation on cookie use with AngularJS so I'm a bit lost with this.

I have two controllers, one creates a cookie and stores a users ID, and then I want to retrieve that ID later when another controller is running. I think I've successfully created the cookie and stored a value for id, however I can't seem to get the id back out of the cookie in the 2nd controller. I get the error in my console when I try to read the id:

TypeError: 'undefined' is not an object

PS: I'm working in Xcode as this is within an ios app for iPhone.

function firstCtrl($scope, $cookieStore) {
    $scope.connectToFacebook = function() {
        FB.api('/me', function(response, data, status, headers, config) {
        var fbid=response.id;
        $cookieStore.put('id', fbid);
        console.log($cookieStore.get('id')); //This correctly displays the users FB id
        });
    }
}

function secondCtrl($scope, $cookieStore) {
    $scope.submit = function() {
    console.log($cookieStore.get('id')); // This is currently displaying: TypeError: 'undefined' is not an object
    };
}
like image 247
AdrianBorkala Avatar asked Feb 23 '13 17:02

AdrianBorkala


1 Answers

Took your advice Greg and went for localstorage instead.

For anyone else having issues and looking for a suitable approach, I used: https://github.com/grevory/angular-local-storage

It degrades gracefully to cookies when localstorage isn't available

Demo available here: http://gregpike.net/demos/angular-local-storage/demo.html

like image 97
AdrianBorkala Avatar answered Nov 15 '22 02:11

AdrianBorkala