Skip to content

Integration with Angular 1.x

Fagner Brack edited this page Dec 23, 2015 · 4 revisions

Reference version: 2.0.3

It is pretty easy to integrate js-cookie with Angular 1.x by creating a simple Factory.

var appModule = angular.module('app', []);

appModule.factory('cookies', function() {
  return Cookies.noConflict();
});

You just need to load js.cookie.js (minified version) before your angular.js file for this to work.

The .noConflict() method is used only in browser environments that load Cookies as a global variable, see the docs here. It is not necessary in UMD or AMD environments, thus we don't expose the .noConflict() method there.

Due to the nature of the "converter" API, it is also possible to easily create specific instances for each server-side encoding type.

Let's take for example PHP, that by default convert spaces ( ) to pluses (+) in the server. To be able to read it, we have to decode it properly using a Factory that creates a new phpCookie instance:

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

The usage would be something like this:

phpCookies.set('name', 'value');
phpCookies.get('name'); // => 'value'