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
             }
         }
     }
Beri
  • 10,277
  • 3
  • 24
  • 47
doe
  • 148
  • 20

2 Answers2

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");
Mihai Dinculescu
  • 18,663
  • 8
  • 48
  • 66
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');
}]);
Community
  • 1
  • 1
Beri
  • 10,277
  • 3
  • 24
  • 47