angularjs - 如何将常量注入(inject)指令的 Controller ?

标签 angularjs dependency-injection

我是依赖注入(inject)的新手,遇到了一些我不太明白的事情。我有一个常量位于单独的文件中,需要将其注入(inject)到指令的同一文件中,以便在指令的 Controller 中使用。我不确定应该在哪里注入(inject)常量:在 Controller 中还是在指令中?这是我的文件的一些示例代码。

第一个文件:

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

第二个文件:

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

谢谢!

最佳答案

您需要将其注入(inject)到.directive函数中。

为此,您可以在函数语句周围放置方括号(以便传递数组而不是单个函数),然后在函数之前添加常量的字符串表示形式,然后添加它作为函数的参数。

模块文件:

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

指令文件:

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

关于angularjs - 如何将常量注入(inject)指令的 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30904853/

相关文章:

javascript - Angular : combine animation with a scope change

javascript - AngularJS 在重复 block 之外和脚本标记中使用 ng-repeat 值

php - 依赖注入(inject)回退可以吗?

logging - 使用 Common.Logging 和 Autofac 的自动化工厂?

angularjs - Angular UI Bootstrap DatePicker initDate 问题

javascript - AngularJS 中的语言环境过滤器 - 如何补偿渲染延迟?

javascript - javascript中是否有必要使用嵌套函数?

java - guice MapBinder 是否公开绑定(bind) key 以进行注入(inject)?

node.js - 如何根据 Onion/Clean Architecture 原则实现 NodeJS 组件?

java - Jersey 2单例依赖注入(inject)创建多个实例