相对于.js文件的Angular指令templateUrl

ped*_*ete 85 javascript path angularjs

我正在构建一个角度指令,它将在几个不同的位置使用.我不能总是保证使用该指令的应用程序的文件结构,但我可以强制用户将directive.jsdirective.html(而不是真正的文件名)放在同一个文件夹中.

当页面评估时directive.js,它认为它templateUrl是相对于它自己的.是否可以将其设置templateUrl为相对于directive.js文件?

或者建议只在模板中包含模板.

我想我可能想根据不同的情况加载不同的模板,所以我宁愿能够使用相对路径而不是更新 directive.js

Alo*_*kin 76

当前正在执行的脚本文件将始终是scripts数组中的最后一个,因此您可以轻松找到其路径:

// directive.js

var scripts = document.getElementsByTagName("script")
var currentScriptPath = scripts[scripts.length-1].src;

angular.module('app', [])
    .directive('test', function () {
        return {
            templateUrl: currentScriptPath.replace('directive.js', 'directive.html')
        };
    });
Run Code Online (Sandbox Code Playgroud)

如果您不确定脚本名称是什么(例如,如果要将多个脚本打包为一个脚本名称),请使用以下命令:

return {
    templateUrl: currentScriptPath.substring(0, currentScriptPath.lastIndexOf('/') + 1) 
        + 'directive.html'
};
Run Code Online (Sandbox Code Playgroud)

注意:在使用闭包的情况下,您的代码应该在外面以确保在正确的时间评估currentScript,例如:

// directive.js

(function(currentScriptPath){
    angular.module('app', [])
        .directive('test', function () {
            return {
                templateUrl: currentScriptPath.replace('directive.js', 'directive.html')
        };
    });
})(
    (function () {
        var scripts = document.getElementsByTagName("script");
        var currentScriptPath = scripts[scripts.length - 1].src;
        return currentScriptPath;
    })()
);
Run Code Online (Sandbox Code Playgroud)

  • 哦,现在那太酷了!不幸的是,这会打破包装和缩小我的js文件,不是吗?另外,为什么'当前正在执行的脚本文件总是最后一个'?我的印象是所有脚本文件都加载到全局范围. (2认同)

Mat*_*Way 6

正如您所说,您希望在指令的不同时间提供不同的模板,为什么不允许模板本身作为属性传递给指令?

<div my-directive my-template="template"></div>

然后$compile(template)(scope)在指令中使用类似的东西.