4

I am making a SPA. On successful login I set the cookies(username,userid,etc.) that contain user information getting from the api.

Set a cookie using PHP :

setcookie("NAME",$records['userinfo']['name'],time()+(20 * 365 * 24 * 60 * 60));

Get it using JavaScript :

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

Try to show in Controller :

angular.module('App', [])

  .controller('UserProfileCtrl', function($scope) {
     function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}
 $scope.username = getCookie('NAME');
  })

index.html :

<html data-ng-app="App" data-ng-controller="AppCtrl">
  <head>
    <link rel="stylesheet" type="text/css" href="css/app.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
    <script src="js/app.js"></script> 
  </head>
  <body data-ng-class="{'skip-animations':disabled}" class="ng-cloak">
        <div class="list-group" data-ng-controller="UserProfileCtrl">
       <p>Welcome</p>
        <div class="username">{{username}}</div>
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 user">
        <div class="user-bg-image">
        <img src="images/user-bg.png">
        <div class="user-img"><img src="{{userimage}}">
        </div>
        </div>
        </div>
        <ul class="user-profile clearfix">
        <a href="#123"><li>Edit Profile</li></a>
        <a href="#123" onclick="logout()"><li>Logout</li></a>
        </ul>
        </div>
    </body>
</html>

It works fine with reloading the app.On reloading we are able to retrieve cookie data (username).

Problem :

How can we retrieve these cookies without reloading the app?

halfer
  • 19,824
  • 17
  • 99
  • 186
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
  • simply call cookie retrival method whenever you want.. – Pankaj Parkar May 12 '15 at 18:27
  • @pankajparkar, it works fine with reloading the page where i want to show the cookie data.But the problem is that i want to show data on the same page without reloading – Debug Diva May 12 '15 at 18:39
  • @pankajparkar, So, you have any idea how can i do that using angular..I am using angular to make SPA.so want to access cookie data without reloading the page, – Debug Diva May 12 '15 at 18:43

2 Answers2

2

You should use ngCookies, is the best way, and in case that you want to persist that data in any part of the DOM, use $cookieStore

anyways, here are the differences

$cookieStore

Provides a key-value (string-object) storage, that is backed by session cookies. Objects put or retrieved from this storage are automatically serialized or deserialized by angular's toJson/fromJson.

$cookies

Provides read/write access to browser's cookies.

Usage, parting from @Dan Doyon answer

<!DOCTYPE html>
<html ng-app="myApp">
<head>
   <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-controller="MyController">

  <h3>Cookies</h3>
  <pre>{{usingCookies|json}}</pre>
  <h3>Cookie Store</h3>
  <pre>{{usingCookieStore|json}}</pre>

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-cookies.js"></script>
  <script>
    angular.module('myApp', ['ngCookies']);
    app.controller('MyController',['$scope','$cookies','$cookieStore', 
                       function($scope,$cookies,$cookieStore) {
      var someSessionObj = { 'innerObj' : 'somesessioncookievalue'};

    $cookies.dotobject = someSessionObj;
    $scope.usingCookies = { 'cookies.dotobject' : $cookies.dotobject, "cookieStore.get" : $cookieStore.get('dotobject') };

    $cookieStore.put('obj', someSessionObj);
    $scope.usingCookieStore = { "cookieStore.get" : $cookieStore.get('obj'), 'cookies.dotobject' : $cookies.obj, };
    }
  </script>

</body>
</html>

and remember

angular.module('myApp', ['ngCookies']);

UPDATE

as per @lucky7id comments, he is right, $cookieStore is deprecated, so just keep using $cookies which is almost the same.

Community
  • 1
  • 1
Reacting
  • 5,543
  • 7
  • 35
  • 86
0

I would suggest using ngCookies, it does a lot of this work for you, including session cookies.

Also, upon successful login, you may want to simply write the cookie in JS, in your callback.

lucky7id
  • 385
  • 1
  • 9
  • i am doing same as suggest by you.cookie is write in JS perfectly but how to show it in same page using angular. – Debug Diva May 12 '15 at 18:41
  • The `$cookies` service has the `get()` and `getObject()` methods, you simply pass the key you stored the cookie as to the appropriate method. https://docs.angularjs.org/api/ngCookies/service/$cookies – lucky7id May 12 '15 at 18:49
  • I passed but how can i show it to the user without refreshing the app. – Debug Diva May 12 '15 at 18:50
  • @RohitJindal Can you update your post to show where you have added the $scope bindings, and corresponding markup? – lucky7id May 12 '15 at 18:56