Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
56
rated 0 times [  57] [ 1]  / answers: 1 / hits: 58683  / 11 Years ago, mon, january 13, 2014, 12:00:00

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.



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.



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


More From » angularjs

 Answers
11

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


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;
})()
);

[#73191] Monday, January 13, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
debra

Total Points: 583
Total Questions: 111
Total Answers: 111

Location: Reunion
Member since Mon, Dec 28, 2020
3 Years ago
;