如何在 AngularJS 中将自定义指令与外部 HTML 模板捆绑在一起

How to bundle a custom Directive with External HTML Template in AngularJS?

本文关键字:HTML 外部 在一起 指令 AngularJS 自定义      更新时间:2023-09-26

请参阅下面的项目结构

project
-Lib
    -MyCustomDirective(which i will use across multiple application)
      -customDir.js
      -customDirTmpl.html
-app
   -js
      -myfirstcontroller.js
      -main.js
   -partials
      -myfirstview.html
   -index.html

因此,我计划创建一个自定义指令,我想在多个项目中使用它。这里的问题是,我想将我的指令的模板保存在单独的 html 文件中。加载指令时,我的应用程序正在尝试查找与当前应用程序对应的"customDirTmpl.html",而不是与我的"MyCustomDirective"文件夹相对应。

我想在所有项目中保持我的指令的 templateUrl 相同,我不想将其分别更改为任何特定项目。

"自定义目录.js"的示例代码

var myDir = function () {
    return {
        restrict: 'E',
        //I want this to be constant accross which ever project i use this directive
        templateUrl: 'customDirTmpl.html',
        link: function(scope){
            //to do something
        }
    };
};
app.directive("MyCustomDir", [myDir]);

执行此操作的一个好方法是在指令库项目中有一个实用程序来处理这些需求。

编写示例将非常乏味,因此这里有一个来自ng-grid项目的示例来演示这一点。查看 getTemplate 函数属性。

这是来自同一项目的示例用法。请注意使用 gridUtil 获取模板。