Stating directive templateUrl relative to root

JavascriptAngularjsAngularjs Directive

Javascript Problem Overview


I am currently stating templateUrl relative to the current window location.

cvApp.directive('personalDetails', function () {

    return {
        restrict: 'A',
        templateUrl: '../../Scripts/app/templates/personalDetails.html'
    };

});

How can I make templateUrl relative to root of the application? I am looking for something like this:

templateUrl: '~/Scripts/app/templates/personalDetails.html'

Can AngularJS accomplish this?

Javascript Solutions


Solution 1 - Javascript

Looks like it's supported. Taken from a thread on AngularJS Google Group:

> the url with "/" prefix is relative to the domain, without the "/" > prefix it will be relative to the main ("index.html") page or base url > (if you use location in the html5 mode).

This works fine:

templateUrl: '/Scripts/app/templates/personalDetails.html'

Solution 2 - Javascript

Looks like you're trying to do ASP.NET style app-relative paths but client-side. The fix is actually in HTML: add a base tag in the head, like this:

<base href="<%= Request.ApplicationPath %>" />

Then keep your template paths relative to this, as in

templateUrl: 'Scripts/app/templates/personalDetails.html'

Solution 3 - Javascript

Use '././Scripts/app/templates/personalDetails.html'

it worked for me.

Solution 4 - Javascript

angular 4 use webpack as bundler.

./ means relative path to current folder



../ means parent folder

domain = src

root = src/index

for example below app.component.ts file, url means xxx.html xxx.css are in the same folder as xxx.ts

./ is relative path as current folder

../ is relative path as parent folder

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})

COMPONENT-RELATIVE PATHS IN ANGULAR

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUfuk HacıoğullarıView Question on Stackoverflow
Solution 1 - JavascriptUfuk HacıoğullarıView Answer on Stackoverflow
Solution 2 - JavascriptBarnabas KendallView Answer on Stackoverflow
Solution 3 - JavascriptRajat FaujdarView Answer on Stackoverflow
Solution 4 - JavascripthoogwView Answer on Stackoverflow