Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js-cookie integration with other frameworks, like AngularJS #103

Closed
FagnerMartinsBrack opened this issue Oct 10, 2015 · 1 comment
Closed
Milestone

Comments

@FagnerMartinsBrack
Copy link
Member

Since js-cookie has no dependencies it is pretty easy to integrate with Angular with a simple service:

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

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

The ".noConflict()" method is used only in browser environments that load Cookies as a global variable. It is not necessary in UMD or AMD environments (they don't expose the .noConflict() method). In this case you just need to include js.cookie.js before angular.js.

Due to the nature of the "converter" API it is also possible to easily create specific instances for each use-case (The implementation below was taken from the write-converters PR):

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 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" );
  }
}]);

It might be worth documenting this somewhere, including any other framework integration that might leverage the way this API was designed.

@FagnerMartinsBrack
Copy link
Member Author

I created a wiki page for this: https://github.com/js-cookie/js-cookie/wiki/Integration-with-Angular-1.x

@FagnerMartinsBrack FagnerMartinsBrack added this to the v2.0.4 milestone Oct 17, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant