Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access cookies in angularJs service

I can succesfully access cookies on my controller like this.

angular.module('mobbr', [ 'ngCookies' ]).    

function RegisterCtrl($scope, $cookies) { }

But whenever i try to use cookies in a service like this.

angular.module('mobbr.services', []);
angular.module('mobbr.services').factory('currentUser', [ 'ngCookies', function ($cookies) {}]);

I get the following error: ngCookiesProvider <- ngCookies <- currentUser.

Any thoughts on why this won't work and how i should initialize a service with acces to cookies?

like image 700
Han Dijk Avatar asked Feb 12 '13 15:02

Han Dijk


People also ask

What is cookies in AngularJS?

AngularJS provides ngCookies module for reading and writing browser cookies. To use it include the angular-cookies. js file and set ngCookies as a dependency in your angular app. This module provides two services for cookie management: $cookies and $cookieStore.

What is the use of dollar cookies in service in AngularJS?

Provides read/write access to browser's cookies. Up until AngularJS 1.3, $cookies exposed properties that represented the current browser cookie values. In version 1.4, this behavior has changed, and $cookies now provides a standard api of getters, setters etc. Requires the ngCookies module to be installed.

How can you set get and clear cookies in AngularJS?

We need to include $cookies in your controller and it has to Get, Set, and Clear method to get, set and clear cookies respectively. Angular has inbuilt directives named as ngCookies.


2 Answers

This is what my code for something similar looks like:

angular.module('app.MyData', ['ngResource','ngCookies']).
    factory('MyService', function($resource, $http, $cookies) {
        ...
    })
like image 111
JeffB Avatar answered Oct 17 '22 11:10

JeffB


For me this worked:

module.controller('myCtrl', ['$scope', '$cookies',
        function($scope, $cookies) {
             ...........
         }
    ]);

Instead of using ngCookies I am using $cookies. I looked at this example but somehow it was throwing error Unknown provider: ngCookiesProvider <- ngCookies

like image 23
SharpCoder Avatar answered Oct 17 '22 11:10

SharpCoder