我可以将templateUrl传递给指令 - AngularJS

时间:2022-03-02 19:42:46

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:

有没有办法将templateUrl传递给我的指令。我知道我可以使用翻译,但这似乎太多了。例如,我有一个widget指令,我想用特定的html填充。有没有办法传递它像:

<div widget templateUrl="template1.html"></div>
<div widget templateUrl="template2.html"></div>

1 个解决方案

#1


33  

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

如果这是一个固定的URL,您可以定义一个指令,如

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.

否则,您可以传递URL,就像将任何其他属性传递给指令一样,并在指令的模板中使用ng-include。

#1


33  

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

如果这是一个固定的URL,您可以定义一个指令,如

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.

否则,您可以传递URL,就像将任何其他属性传递给指令一样,并在指令的模板中使用ng-include。