AngularJS - 在 templateUrl 中具有属性的自定义指令

AngularJS - custom directive with attributes in templateUrl

我有一些格式文本模板,例如 frecuencia-dia.htmlfrecuencia-mes.html .

我想使用属性 tipo(纯文本)和 clave(可变范围)调用动态模板。

<ng-formato-texto tipo="frecuencia" clave="{{prod.claveFrecuencia}}" />

app.directive('ngFormatoTexto', function() {
    return {
        templateUrl: function(elem, attr){
            return '/formats/'+attr.tipo+'-'+attr.clave+'.html';
        }
    };
});

但是不行,这个试试 load frecuencia-%7B%7Bprod.clavePrueba%7D%7D.html

您不能在指令中使用动态模板。

如文档所述:

Note: You do not currently have the ability to access scope variables from the templateUrl function, since the template is requested before the scope is initialized.

创建动态指令可以使用ng-include.

示例:

app.directive('ngFormatoTexto', function() {
 return {
     template: '<div ng-include="path"></div>',
     scope:{
       tipo:"@",
       clave:"="
     },
     link:function(scope){
       scope.path= '/formats/'+scope.tipo+'-'+scope.clave+'.html'
     }
 };
});