指令templateUrl相对.js文件角 [英] Angular directive templateUrl relative to .js file

查看:134
本文介绍了指令templateUrl相对.js文件角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建一个角指令,它会在几个不同的位置使用。
我不能总是保证指令中所使用的应用程序的文件结构,但我可以强制用户把 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.

我想我可能要根据不同的情况下加载不同的模板,所以将preFER才能够使用相对路径,而不是更新 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'
};

注意的:在使用封闭的情况下,你的code外应,以确保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;
    })()
);

这篇关于指令templateUrl相对.js文件角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆