invertere
invertere

Reputation: 33

How can I inject a constant into a directive's controller?

I'm new to dependency injections and have encountered a something I can't quite figure out. I have a constant located in a separate file and need it injected into the same file of my directive to be used in the directive's controller. I'm unsure of where I should be injecting the constants: in the controller or the directive? Here's some example code of what my files sort of look like.

First file:

angular.module('utilities')
    .constant('myOpts', {
        ...stuff
    });

Second file:

angular.module('main')
.directive('myDirective', function() {
    return {
        controller: function () {
            ... need the constant in here
        }
    }
});

Thank you!

Upvotes: 2

Views: 5467

Answers (1)

Le-roy Staines
Le-roy Staines

Reputation: 2057

You need to inject it into the .directive function.

You do this by putting square brackets around your function statement (so that you are passing and array instead of a single function) and then prepending the string representation of your constant before the function, then adding it as a parameter of your function.

Module file:

angular.module('utilities')
    .constant('myOpts', {
        'stuff1': 'Stuff 1 Value',
        'stuff2': 'Stuff 2 Value'
    });

Directive file:

angular.module('main')
.directive('myDirective', ['myOpts', function(myOpts) {
    return {
        controller: function () {
            alert(myOpts.stuff1);
            alert(myOpts.stuff2);
        }
    }
}]);

Upvotes: 2

Related Questions