Angularjs cookies - 如何跨控制器使用它们

时间:2022-06-20 10:53:59

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

似乎没有任何关于使用AngularJS的cookie的真正明确的文档,所以我有点迷失了。

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:

我有两个控制器,一个创建一个cookie并存储一个用户ID,然后我想在以后另一个控制器运行时检索该ID。我想我已经成功创建了cookie并为id存储了一个值,但是我似乎无法从第二个控制器中的cookie中取出id。当我尝试读取id时,我在控制台中收到错误:

TypeError: 'undefined' is not an object

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

PS:我在Xcode工作,因为这是在iPhone的ios应用程序中。

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
    };
}

1 个解决方案

#1


7  

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

对于其他任何有问题并寻找合适方法的人,我使用过:https://github.com/grevory/angular-local-storage

It degrades gracefully to cookies when localstorage isn't available

当localstorage不可用时,它会优雅地降级为cookie

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

可在此处获得演示:http://gregpike.net/demos/angular-local-storage/demo.html

#1


7  

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

对于其他任何有问题并寻找合适方法的人,我使用过:https://github.com/grevory/angular-local-storage

It degrades gracefully to cookies when localstorage isn't available

当localstorage不可用时,它会优雅地降级为cookie

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

可在此处获得演示:http://gregpike.net/demos/angular-local-storage/demo.html