Home » Angularjs » Can I pass the templateUrl to the directive – AngularJS

Can I pass the templateUrl to the directive – AngularJS

Posted by: admin December 7, 2017 Leave a comment

Questions:

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>
Answers:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *