Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass the templateUrl to the directive - AngularJS

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>
like image 519
jhamm Avatar asked Nov 02 '13 13:11

jhamm


People also ask

What is templateUrl in AngularJS?

templateUrl can also be a function which returns the URL of an HTML template to be loaded and used for the directive. AngularJS will call the templateUrl function with two parameters: the element that the directive was called on, and an attr object associated with that element.

Which of the following is not an AngularJS directive?

ng-state is not an AngularJS directive. Q 15 - Which of the following is true about ng-app directive? A - ng-app directive defines and links an AngularJS application to HTML.

What is the difference between controller and link in directives?

Answer:The link option is just a shortcut to setting up a post-link function. controller: The directive controller can be passed to another directive linking/compiling phase. It can be injected into other directices as a mean to use in inter-directive communication.


1 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.

like image 65
Andyrooger Avatar answered Oct 19 '22 07:10

Andyrooger