gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:45:42 24 4
gpt4 key购买 nike

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

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

或者建议只在指令本身中包含模板。

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

最佳答案

当前执行的脚本文件永远是脚本数组中的最后一个,所以你可以很容易地找到它的路径:

// 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')
};
});

如果您不确定脚本名称是什么(例如,如果您将多个脚本打包成一个),请使用:

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

注意:在使用闭包的情况下,您的代码应该在外部以确保在正确的时间评估 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;
})()
);

关于javascript - 相对于 .js 文件的 Angular 指令 templateUrl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21103724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com