我正在创建一个指令,其中我有一个带有变量type
的范围(本地),并且我应该返回相应的模板。 chooseTemplateByType
会根据type
返回一个包含相应模板的字符串,例如text_field
。
template:
chooseTemplateByType(type)
问题是如何访问我的本地范围的变量类型,以便我可以将值传递给我的函数chooseTemplateByType
答案 0 :(得分:3)
实现此目的的最佳方法是通过属性将type
变量传递给您的指令。
HTML
<my-directive type="foo"></my-directive>
JS
myApp.directive('myDirective', function() {
return {
template: function(elem, attr){
return "<h1>" + attr.type + "</h1>"; // will output <h1>foo</h1>
}
};
});
OR
myApp.directive('myDirective', function() {
return {
templateUrl: function(elem, attr){
return attr.type + '.html'; // will load foo.html
}
};
});