17

Is there a way to pass a templateUrl to my directive. I understand I can use transclusion, but that seems too much. For example, I have a widget directive that I want to fill with specific html. Is there a way to pass it in like:

<div widget templateUrl="template1.html"></div>
<div widget templateUrl="template2.html"></div>
jhamm
  • 24,124
  • 39
  • 105
  • 179

1 Answers1

34

If this is a fixed URL you can define a directive such as

app.directive('myDirective', function() {
    return {
        templateUrl: function(tElement, tAttrs) {
            return tAttrs.templateUrl;
        }
    };
});

then use it like this

<div my-directive template-url="template1.html"></div>

Otherwise you could pass the URL as you would pass any other attribute into a directive and use ng-include in your directive's template.

Andyrooger
  • 6,748
  • 1
  • 43
  • 44
  • 2
    You cannot use function as `templateUrl` in Angular 1.0.8 so be sure to use at least Angular 1.1.4. – lort Nov 02 '13 at 14:08
  • 1
    Good point. It's been a while since I've used stable branch! `ng-include` should still work though either way. – Andyrooger Nov 02 '13 at 14:16
  • Is it posible that passing variable to template-url instead template1.html? @Andyrooger – ddagsan Feb 27 '17 at 14:13
  • 1
    @ddagsan If you're talking about using template-url like an `'='` bound scope member, then I don't think it's possible. You'd need access to a scope, but I think the template function will run before that's available. This answer is quite old now though, so there may be a better way to deal with this whole problem now in newer versions of angular. – Andyrooger Feb 27 '17 at 15:17
  • I was looking for how to do this with a component vs. a directive, but your answer got me closer to my answer, $element & $attrs: https://stackoverflow.com/a/33846452/3507333 – madannes Jan 30 '18 at 21:52