Kichu
Kichu

Reputation: 1731

Angularjs is not reading cookie

My server side I am using php. I just set one cookie using php.

setcookie("authtoken", $_SESSION['token']);

It's available in browser cookie.

My client side I am using angularJs.I try to read the cookies using angular js things.But I am getting undefined

<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-cookies.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', ['ngCookies']);
        app.controller('MyController', function ($scope, $window, $cookieStore) {

            $scope.ReadCookie = function () {
                $window.alert($cookieStore.get('authtoken'));
            };

        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        Name:
        <input type="text" ng-model="Name" />
        <br />
        <br />
        <input type="button" value="Read Cookie" ng-click="ReadCookie()" />

    </div>
</body>
</html>

please suggest way to solve this problem.

Thanks In advance!!

Upvotes: 0

Views: 328

Answers (1)

macl
macl

Reputation: 995

If cookie was not set by angular, you must use the $cookies service, and not $cookieStore. $cookieStore serializes and deserializes cookies in JSON format. To retrieve the value, code should be:

$window.alert($cookies.authtoken);

Of course, you should inject it with:

app.controller('MyController', function ($scope, $window, $cookies) {

Upvotes: 1

Related Questions