javascript - Angular 指令代替 ng-include

标签 javascript angularjs angularjs-directive

我有以下代码:

angular.module('app')
    .directive('directiveA', function () {
          return {
            templateUrl: '/template-a.html'
          };
        }
    )
    .directive('directiveB', function () {
          return {
            templateUrl: '/template-b.html'
          };
        }
    )
    .directive(// I hope you got the point.

该代码不是很干燥,我更喜欢使用 ng-include,但这些指令非常好,例如页脚、页眉、闪存消息等,并且允许编写非常易读的 HTML,因此最好拥有它们。

我能否以某种方式向 angular.module 添加额外的方法,例如 viewDirective,以这种方式描述指令:

angular.module('app')
    .viewDirective('directiveA', '/template-a.html')
    .viewDirective('directiveB', '/template-b.html')
    ...

我可以将它添加到angular.module.prototype中吗?或者有更好的方法来扩展模块方法吗?类似的东西已经在 Angular 中实现了,所以我不发明轮子吗?或者使用ng-include更好?

最佳答案

如果保留指令名称和路径约定,则可以执行以下操作:

var directiveNames = ['a', 'b', 'c'];
_.forEach(directiveNames, function (name) {
    angular.module('app').directive(name, function () {
        return {
            templateUrl: '/' + name + '.html'
        }
    )
 });

您可以在此处找到对 Angular 本身的引用,以编程方式使用 DRY 原则创建自己的指令: https://github.com/angular/angular.js/blob/d077966ff1ac18262f4615ff1a533db24d4432a7/src/ng/directive/ngEventDirs.js (第 49 行)

关于javascript - Angular 指令代替 ng-include,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36187483/

相关文章:

javascript - 获取相对定位元素的 href

angularjs - Angular ng-if 仍在运行

javascript - 用于跨浏览器 SELECT Dropdown 的 AngularJs 指令

javascript - 意外 'continue'

javascript - Highcharts:从具有多个系列的图中选择单个系列

javascript - 在 javascript 中从 prompt.get trim 换行符

javascript - 如果数组没有元素,如何使条件为真?

javascript - 将代码包装到闭包中是一个好习惯吗?

Angularjs指令: accessing sibling elements in link function

angularjs - 指令如何通过 Controller 进行通信?