Pregunta

I've been trying to use ngCookie to store and retrieve cookies in my app. Since I can't set the path or expiration of the cookies created with ngCookie, I've had to look elsewhere.

So I'm attempting to use this jQuery cookie plugin.

However, I can't figure out how to make it available in an angular service. Gooling around for how to make jQuery plugins available in controllers and services, the answers unanimously point to using directive, but I don't think that's the right approach in this case since cookies are something controllers and services should be aware of.

So, how would someone make a jQuery plugin available to an Angular service?

¿Fue útil?

Solución

You can encapsulate the jquery cookie API in a factory will expose some methods like that:

angular.module('MyApp', []);

angular.module('MyApp').factory('CookieFactory', function(){

    return {
        getCookie: function(name){
            return $.cookie(name);
        },

        getAllCookies: function(){
            return $.cookie();
        },

        setCookie: function(name, value){
            return $.cookie(name, value);
        },

        deleteCookie: function(name){
            return $.removeCookie(name);
        }
    }
});

But we can easyli imagine that you want to do something when you get the cookie value. What about a callback via the API promise of AngularJS.

So our factory becomes :

angular.module('MyApp', []);

angular.module('MyApp').factory('CookieFactory', function($q, $timeout){

    return {
        getCookie: function(name){
           var deferred = $q.defer();

           $timeout(function() {
               deferred.resolve($.cookie(name));
           }, 0);

           return deferred.promise;
        },

        getAllCookies: function(){
            return $.cookie();
        },

        setCookie: function(name, value){
            return $.cookie(name, value);
        },

        deleteCookie: function(name){
            return $.removeCookie(name);
        }
    }
});

Then you can use it in your controller like that :

angular.module('MyApp').controller('CookieCtrl', function(CookieFactory) {

    CookieFactory.getCookie('mycookie').then(function(value){
      //do that you want
    });

});

Working plunkr here : http://plnkr.co/edit/6KoUtp?p=preview

Otros consejos

I think this is one instance where you would want to use a service instead of a directive. Typically, a directive would be used when you deal with jQuery plugins that modify DOM elements.

It would look something like this.

angular.module('app', []).service('myCookieService', function(){
    return {
        cookie: $.cookie,
        removeCookie: $.removeCookie
    }
});

Of course, having said that, you could just call the jQuery plugin from anywhere in your app.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top