[angularjs] How to access cookies in AngularJS?

What's the AngularJS way to access cookies? I've seen references to both a service and a module for cookies, but no examples.

Is there, or is there not an AngularJS canonical approach?

This question is related to angularjs angular-cookies

The answer is


AngularJS provides ngCookies module and $cookieStore service to use Browser Cookies.

We need to add angular-cookies.min.js file to use cookie feature.

Here is some method of AngularJS Cookie.

  • get(key); // This method returns the value of given cookie key.

  • getObject(key); //This method returns the deserialized value of given cookie key.

  • getAll(); //This method returns a key value object with all the cookies.

  • put(key, value, [options]); //This method sets a value for given cookie key.

  • remove(key, [options]); //This method remove given cookie.

Example

Html

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular-cookies.min.js"></script>
</head>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.
</body>
</html>

JavaScript

var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);

I have Taken reference from http://www.tutsway.com/simple-example-of-cookie-in-angular-js.php.


FYI, I put together a JSFiddle of this using the $cookieStore, two controllers, a $rootScope, and AngularjS 1.0.6. It's on JSFifddle as http://jsfiddle.net/krimple/9dSb2/ as a base if you're messing around with this...

The gist of it is:

Javascript

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

myApp.controller('CookieCtrl', function ($scope, $rootScope, $cookieStore) {
    $scope.bump = function () {
        var lastVal = $cookieStore.get('lastValue');
        if (!lastVal) {
            $rootScope.lastVal = 1;
        } else {
            $rootScope.lastVal = lastVal + 1;
        }
        $cookieStore.put('lastValue', $rootScope.lastVal);
    }
});

myApp.controller('ShowerCtrl', function () {
});

HTML

<div ng-app="myApp">
    <div id="lastVal" ng-controller="ShowerCtrl">{{ lastVal }}</div>
    <div id="button-holder" ng-controller="CookieCtrl">
        <button ng-click="bump()">Bump!</button>
    </div>
</div>

The original accepted answer mentions jquery.cookie plugin. A few months ago though, it was renamed to js-cookie and the jQuery dependency removed. One of the reasons was just to make it easy to integrate with other frameworks, like Angular.

Now, if you want to integrate js-cookie with angular, it is as easy as something like:

module.factory( "cookies", function() {
  return Cookies.noConflict();
});

And that's it. No jQuery. No ngCookies.


You can also create custom instances to handle specific server-side cookies that are written differently. Take for example PHP, that convert the spaces in the server-side to a plus sign + instead of also percent-encode it:

module.factory( "phpCookies", function() {
  return Cookies
    .noConflict()
    .withConverter(function( value, name ) {
      return value
            // Decode all characters according to the "encodeURIComponent" spec
            .replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
            // Decode the plus sign to spaces
            .replace(/\+/g, ' ')
    });
});

The usage for a custom Provider would be something like this:

module.service( "customDataStore", [ "phpCookies", function( phpCookies ) {
  this.storeData = function( data ) {
    phpCookies.set( "data", data );
  };
  this.containsStoredData = function() {
    return phpCookies.get( "data" );
  }
}]);

I hope this helps anyone.

See detailed info in this issue: https://github.com/js-cookie/js-cookie/issues/103

For detailed docs on how to integrate with server-side, see here: https://github.com/js-cookie/js-cookie/blob/master/SERVER_SIDE.md



This is how you can set and get cookie values. This is what I was originally looking for when I found this question.

Note we use $cookieStore instead of $cookies

<!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, $cookieStore) {
      $scope.lastVal = $cookieStore.get('tab');

      $scope.changeTab = function(tabName){
          $scope.lastVal = tabName;
          $cookieStore.put('tab', tabName);
      };
    }
  </script>
</head>
<body ng-controller="CookieCtrl">
    <!-- ... -->
</body>
</html>

Here's a simple example using $cookies. After clicking on button, the cookie is saved, and then restored after page is reloaded.

app.html:

<html ng-app="app">
<head>
    <meta charset="utf-8" />
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-cookies.js"></script>
    <script src="app.js"></script>
</head>
<body ng-controller="appController as vm">

    <input type="text" ng-model="vm.food" placeholder="Enter food" />

    <p>My favorite food is {{vm.food}}.</p>

    <p>Open new window, then press Back button.</p>
    <button ng-click="vm.openUrl()">Open</button>
</body>
</html>

app.js:

(function () {
    "use strict";

    angular.module('app', ['ngCookies'])
    .controller('appController', ['$cookies', '$window', function ($cookies, $window) {
        var vm = this;

        //get cookie
        vm.food = $cookies.get('myFavorite');

        vm.openUrl = function () {
            //save cookie
            $cookies.put('myFavorite', vm.food);
            $window.open("http://www.google.com", "_self");
        };
    }]);

})();

Add angular cookie lib : angular-cookies.js

You can use $cookies or $cookieStore parameter to the respective controller

Main controller add this inject 'ngCookies':

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

Use Cookies in your controller like this way:

 app.controller('checkoutCtrl', function ($scope, $rootScope, $http, $state, $cookies) { 

//store cookies

 $cookies.putObject('final_total_price', $rootScope.fn_pro_per);

//Get cookies

 $cookies.getObject('final_total_price'); }

Angular deprecated $cookieStore in version 1.4.x, so use $cookies instead if you are using latest version of angular. Syntax remain same for $cookieStore & $cookies:

$cookies.put("key", "value"); 
var value = $cookies.get("key");

See the Docs for an API overview. Mind also that the cookie service has been enhanced with some new important features like setting expiration (see this answer) and domain (see CookiesProvider Docs).

Note that, in version 1.3.x or below, $cookies has a different syntax than above:

$cookies.key = "value";
var value = $cookies.value; 

Also if you are using bower, make sure to type your package name correctly:

bower install [email protected] 

where X.Y.Z is the AngularJS version you are running. There's another package in bower "angular-cookie"(without the 's') which is not the official angular package.