David Dury
David Dury

Reputation: 5717

AngularJS use constant in directive

I have defined a constant like this:

app.constant('ngSettings', {
    apiBaseUrl: 'https://url/'
});

how can I reference now this constant in a directive?

Where the directive is something like this:

angular.module('my.directive', []).directive(...................

Upvotes: 4

Views: 6580

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191779

You can inject the constant anywhere that is injectable including the directive definition itself, the controller of a directive, the link function, et. al.

angular.module('my.directive', []).directive('name', ['ngSettings', function (ngSettings) {
    // do things with ngSettings
    return {};
}]);

By the way I wouldn't name anything you define yourself as ng -- that should be preserved for things in the ng module or that Angular itself created.

Upvotes: 13

Estus Flask
Estus Flask

Reputation: 222760

The same way as you would use any other dependency.

angular.module('my.directive', []).directive('my', ['ngSettings', function (ngSettings) {
    ...
}]);

Constants are particular cases of providers:

The remaining four recipe types — Value, Factory, Service and Constant — are just syntactic sugar on top of a provider recipe.

Upvotes: 0

Related Questions