Adrian E
Adrian E

Reputation: 2093

Using $cookies in controller generates TypeError: undefined is not a function

UPDATE: ISSUE RESOLVED

Turns out I was not aware that the ngCookies was a separate service which is not part of the standard angular.js. My bower.json file was referencing angular 1.4beta but the angular-cookies was still loading 1.3. I changed that to 1.4beta and everything is working as expected.

I am using $cookies in a controller in an Angular 1.4 project but I am getting the following error when I reference $cookies:

TypeError: undefined is not a function
    at Object.<anonymous> (http://localhost:9000/bower_components/angular-cookies/angular-cookies.js:60:16)
    at Object.invoke (http://localhost:9000/bower_components/angular/angular.js:4371:17)
    at Object.enforcedReturnValue [as $get] (http://localhost:9000/bower_components/angular/angular.js:4224:37)
    at Object.invoke (http://localhost:9000/bower_components/angular/angular.js:4371:17)
    at http://localhost:9000/bower_components/angular/angular.js:4189:37
    at getService (http://localhost:9000/bower_components/angular/angular.js:4330:39)
    at invoke (http://localhost:9000/bower_components/angular/angular.js:4362:13)
    at Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:4379:27)
    at http://localhost:9000/bower_components/angular/angular.js:8668:28
    at link (http://localhost:9000/bower_components/angular-route/angular-route.js:981:26) <div ng-view="" class="ng-scope">

My code:

angular.module('supportalApp', [
'ngCookies',
'ngAnimate',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'cfp.hotkeys',
'ngClipboard']);
angular.module('supportalApp')
  .controller('ToolsCtrl', function($scope, $cookies) {....
  });

If I remove $cookies, no errors are rendered. And just to confirm, I have included 'ngCookie' in the app

Upvotes: 0

Views: 3570

Answers (2)

Sandro Giessl
Sandro Giessl

Reputation: 674

Note that the $cookies API used to be an associative array before AngularJS v1.4.0-beta.6, and the online documentation (defaulting to a development snapshot) already refers to the new get/put API. The relevant change is https://github.com/angular/angular.js/commit/38fbe3ee8370fc449b82d80df07b5c2ed2cd5fbe

With AngularJS <= v1.4.0-beta.5, you have the following choices:

  • Use $cookieProvider
  • $cookies["key"] = value
  • $cookies.key = value
  • (Upgrade AngularJS)

Upvotes: 3

BeingDev
BeingDev

Reputation: 426

I don't see 'ngCookies' added in your module dependency, please add it.

angular.module('supportalApp', ['ngCookies'])
  .controller('ToolsCtrl', function($scope, $cookies) {....
});

Upvotes: 3

Related Questions