我有以下代码:
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/