0
votes

The syntax for dependency injection in Angular.js is confusing me.

I have a Rails app that is using Angular. One of the directives needs to use the $cookies service. So I have the main Javascript file where I declare the angular app, and a directives folder with js-files for my directives.

So this is the relevant part of the main js file. I'm trying to inject the ngCookies module into it:

app.js

angular.module('myApp', [
  'templates',
  'ngCookies'
]);

and here is the file with the directive that needs the $cookies service:

my-directive.js

angular.module('myApp')
  .directive("myDirective", ['$cookies', function(){
    return {
      restrict: 'E'
      templateUrl: "my-directive-template.html",
      scope: {
        article: '=ngModel'
      },
      link: function(scope, element, attrs){
        scope.myFunction = function(){
          $cookies.example = "hello world"; // set a cookie
        };
      }
    };
  }]);

So I'm trying to inject the ngCookies module into the myApp module and then inject the $cookies service into the directive.

This syntax doesn't work; Firebug gives me an error: "Error: $cookies is undefined".

Could you please help me figure out how to inject dependencies in Angular properly?

1

1 Answers

0
votes

Oh my! I guess the only thing I needed was to add the $cookies as an attribute for the function declaration as well so that the line

.directive("myDirective", ['$cookies', function(){

became

.directive("myDirective", ['$cookies', function($cookies){