相对于 .js 文件的 Angular 指令 templateUrl [英] Angular directive templateUrl relative to .js file
问题描述
我正在构建一个 angular 指令,它将在几个不同的位置使用.我不能总是保证使用指令的应用程序的文件结构,但我可以强制用户放置 directive.js
和 directive.html
(不是真实文件名)在同一文件夹中.
I'm building an angular directive which will be used in a few different locations.
I can't always guarantee the file structure of the app the directive is used in, but I can force the user to put the directive.js
and directive.html
(not the real file names) in the same folder.
当页面评估 directive.js
时,它认为 templateUrl
是相对于自身的.是否可以将 templateUrl
设置为相对于 directive.js
文件?
When the page evaluates the directive.js
, it considers the templateUrl
to be relative to itself. Is it possible to set the templateUrl
to be relative to the directive.js
file?
或者建议只在指令本身中包含模板.
Or is it recommended to just include the template in the directive itself.
我想我可能想根据不同的情况加载不同的模板,所以我希望能够使用相对路径而不是更新 directive.js
I'm thinking I may want to load different templates based on different circumstances, so would prefer to be able to use a relative path rather than updating the directive.js
推荐答案
当前正在执行的脚本文件将始终是脚本数组中的最后一个,因此您可以轻松找到其路径:
The currently executing script file will always be the last one in the scripts array, so you can easily find its path:
// 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')
};
});
如果您不确定脚本名称是什么(例如,如果您将多个脚本打包成一个),请使用:
If you're not sure what is the script name (for example if you're packing multiple scripts into one), use this:
return {
templateUrl: currentScriptPath.substring(0, currentScriptPath.lastIndexOf('/') + 1)
+ 'directive.html'
};
注意:在使用闭包的情况下,您的代码应该在外部以确保在正确的时间评估 currentScript,例如:
Note: In cases where a closure is used, your code should be outside to ensure that the currentScript is evaluated at the correct time, such as:
// 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;
})()
);
这篇关于相对于 .js 文件的 Angular 指令 templateUrl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!