0

I have a directive that looks like this:

angular.module('customDirectives', [])
.directive('searchResult', function() {
    return {
        templateUrl: 'app/directives/templates/searchResult.html',
        replace: true,
        scope: {
            itemObject: "=",
            itemById: "&"
        }
    }
});

It works, but I would like to have a templateUrl like "templates/searchResult.html" since the template folder is right next to my directive file. But it seems like I need to give the location of my template depending on where is my index.html file... Is there anyway to change the templateUrl to "templates/searchResult.html"?

Kévin Duguay
  • 761
  • 3
  • 12
  • 29
  • 'app/directives/templates/searchResult.html' is a relative path. If that is actually how you have the site structured you might just move the templates folder up two nodes. – errata Jan 18 '16 at 23:47
  • My goald would be that the path be just 'templates/searchResult.html' so that if I would need my directives in an other project, I could just copy/paste the directive folder whitout having to change ALL my directives templateUrl. – Kévin Duguay Jan 19 '16 at 00:10
  • Refer to the answer suggested in https://stackoverflow.com/questions/21103724/angular-directive-templateurl-relative-to-js-file — it does seem a little hacky, but it's a good workaround. – miqh Jan 19 '16 at 00:47

1 Answers1

0

I think I have a workaround for it. If you are sure, that you will have all your directives in one place, just use an angular constant to store your root folder url. In order to do this, firstly add a constant to your app module, for example:

angular.module('app', ['customDirectives'])
    .constant('appConfig', {
         directivesRoot: 'app/directives/'
     });

Then, in your directive, inject the appConfig and use it like this:

angular.module('customDirectives', [])
.directive('searchResult', ['appConfig', function(appConfig) {
    return {
        templateUrl: appConfig.directivesRoot + 'templates/searchResult.html',
        replace: true,
        scope: {
            itemObject: "=",
            itemById: "&"
        }
    }
}]);

If you want to use directives in another project, you will need to change only the directivesRoot url.

PJDev
  • 951
  • 5
  • 20