AngularJS在指令中使用constant

时间:2015-04-09 20:32:37

标签: angularjs angularjs-directive

我已经定义了一个这样的常量:

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

如何在指令中引用此常量?

指令是这样的:

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

2 个答案:

答案 0 :(得分:12)

您可以在任何可注射的位置注入常量,包括指令定义本身,指令的控制器,链接函数等。人

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

顺便说一下,我不会将你自己定义的任何内容命名为ng - 应该保留ng模块中的内容或Angular本身创建的内容。

答案 1 :(得分:0)

与使用任何其他依赖项的方式相同。

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

常量是providers的特殊情况:

  

其余四种配方类型 - 价值,工厂,服务和常数    - 只是提供者食谱之上的语法糖。