0

I can get a cookie as the following. I call this cookie in my module and pass it as a parameter.

How do I change the code to get a cookie so that its all in standard angularjs code?

    $(document).ready(function() {
         Cookie();
     });

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

     function Cookie() {
         var cookie = getCookie('Id');

     }

     function Module($http) {
         var self = this;
         self.$http = $http;
         self.CookieID = getCookie('Id');

         self.test = function() {
             var params = {
                 testId: self.CookieID
             }
         }
     }
2
  • methinks you need ngCookies Commented Apr 29, 2015 at 9:23
  • yeah im not sure how to use it,since i already hv the id set in another page Commented Apr 29, 2015 at 9:32

2 Answers 2

3

Angular ngCookies

First include angular-cookies.js in your HTML:

<script src="angular.js">
<script src="angular-cookies.js">

Then load the module in your application by adding it as a dependent module:

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

Usage Example

angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
  // Retrieving a cookie
  var favoriteCookie = $cookies.get('myFavorite');
  // Setting a cookie
  $cookies.put('myFavorite', 'oatmeal');
}]);

jQuery

Set Cookie

$.cookie("my_cookie", value);

Set Cookie with Expiration (in days) and Path

$.cookie("my_cookie", value, { expires: 1, path: '/' });

Remove Cookie

$.removeCookie("my_cookie");
Sign up to request clarification or add additional context in comments.

4 Comments

i tired this,but nothing gets passed to my parameter
I have updated my answer with jQuery support as well.
i have to use angular js
i used local storage service instead link
0

Have you tried $cookies?

Secondly you could use jQuery cookie - if AngularJs cookie won't do for you.

Example:

angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
  // Retrieving a cookie
  var favoriteCookie = $cookies.get('myFavorite');
  // Setting a cookie
  $cookies.put('myFavorite', 'oatmeal');
}]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.