0

I have a problem with my AngularJS app. I'm trying to get the browser cookies but when I try to access the cookies it's always empty, I've tried it in Safari, Firefox and Chrome. I found this example below that many confirms work but I can't get it to work, see my comments for the output I'm getting.

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
  <script src="http://code.angularjs.org/1.0.0rc10/angular-cookies-1.0.0rc10.js"></script>
  <script>
    angular.module('myApp', ['ngCookies']);
    function CookieCtrl($scope, $cookies) {
      console.log($cookies) // FireBug: Object { }
      $scope.cookieValue = $cookies.text;
    }
  </script>
</head>
<body ng-controller="CookieCtrl">

Cookie Value: '{{cookieValue}}' <!-- Cookie Value: '' -->

</body>
</html>

I don't get any other errors that indicates that something is wrong.

Thank you in advance, Mattias

Mattias Farnemyhr
  • 4,148
  • 3
  • 28
  • 49
  • Can you show the code where you SET the cookie to a value? – Phil Sandler Dec 10 '13 at 16:13
  • I actually don't want to set the cookie myself, I just want to get the cookie that I use to authenticate my Django app so I use it when requesting it. I thought I could login on another tab in my browser and get the cookie from my AngularJS app? – Mattias Farnemyhr Dec 10 '13 at 16:21
  • Did you verify that the cookie exists before trying to access it? You can generally do this by inspecting the page using developers tools. – Phil Sandler Dec 10 '13 at 16:27
  • Yes, I use FireBug and in the Cookies tab it says that there are 5 cookies, all from my Django app, these are the ones I want. – Mattias Farnemyhr Dec 10 '13 at 16:37
  • 1
    Maybe set up a plunker or jsfiddle? Seems like your code should work. Your angular app is in the same domain as the cookies, correct? – Phil Sandler Dec 10 '13 at 16:55
  • Try [$cookieStore](http://docs.angularjs.org/api/ngCookies.$cookieStore). I had problems with $cookies as well, but $cookieStore was perfect. – Zack Argyle Dec 10 '13 at 17:03
  • @PhilSandler thanks phil, that was the problem, I had my frontend and my backend on different domains and when I changed it, it worked. is there any way to get it working on different domains though? – Mattias Farnemyhr Dec 10 '13 at 21:11
  • Cookies are specific to domains. You would have to do some kind of redirect trick to make something like that work. See answer here: http://stackoverflow.com/a/3342225/151084 – Phil Sandler Dec 10 '13 at 21:14

1 Answers1

0

As noted in comments, you can only access cookies from the current domain. This is not a limitation of Angular; this is simply how cookies work.

Phil Sandler
  • 27,544
  • 21
  • 86
  • 147