What’s the AngularJS way to access cookies? I’ve seen references to both a service and a module for cookies, but no examples.
Is there, or is there not an AngularJS canonical approach?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This answer has been updated to reflect latest stable angularjs version. One important note is that
$cookieStoreis a thin wrapper surrounding$cookies. They are pretty much the same in that they only work with session cookies. Although, this answers the original question, there are other solutions you may wish to consider such as using localstorage, or jquery.cookie plugin (which would give you more fine-grained control and do serverside cookies. Of course doing so in angularjs means you probably would want to wrap them in a service and use$scope.applyto notify angular of changes to models (in some cases).One other note and that is that there is a slight difference between the two when pulling data out depending on if you used
$cookieto store value or$cookieStore. Of course, you’d really want to use one or the other.In addition to adding reference to the js file you need to inject
ngCookiesinto your app definition such as:you should then be good to go.
Here is a functional minimal example, where I show that
cookieStoreis a thin wrapper around cookies:The steps are:
angular.jsangular-cookies.jsngCookiesinto your app module (and make sure you reference that module in theng-appattribute)$cookiesor$cookieStoreparameter to the controller— OR —
cookieStoreusing put/get methods