AngularJS Cookie Service

Thu, 18 Dec 2014

In case you're searching for a cookie service that can be used in AngularJS, here it is:

'use strict'

angular .module('APP.services', []) .factory('Cookie', function() { var self = this;

self.set = function(name, value, days) {
	var expires = "";

	if(days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	} else {
		expires = "";
	}

	document.cookie = name + "=" + value + expires + "; path=/";
};

self.get = function(name) {
	var nameEQ	= name + "=",
		ca		= document.cookie.split(';');

	for(var i=0; i<ca.length; ++i) {
		var c = ca[i];
		while(c.charAt(0)==' ') {
			c = c.substring(1,c.length);
		}

		if(c.indexOf(nameEQ) === 0) {
			return c.substring(nameEQ.length,c.length);
		}
	}

	return null;
};

self.remove = function(name) {
	self.put(name, "", -1);
};

return {
	set:	self.set,
	get:	self.get,
	remove:	self.remove
};

})

;

Usage:

'use strict'

angular .module('APP.home', ['APP.services']) .controller('TestController', ['Cookie', function(Cookie) {

// Set cookie
Cookie.set('cookie_name', 'VALUE', 1);

// Get cookie
if(Cookie.get('cookie_name')) {
    console.log(Cookie.get('cookie_name'));
}

// Remove cookie
Cookie.remove('cookie_name');

}])

;

Categories: angularjs