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