Angular 指令不同的模板 [英] Angular Directive Different Template
问题描述
我有一个变量类型的指令 myDirective.如果我运行 <my-directive type="X">
我希望指令使用 templateUrl: x-template.html.如果我执行 <my-directive type="Y">
我希望指令使用 templateUrl: y-template.html.
I have a directive myDirective with variable type. If I run <my-directive type="X">
I want the directive to use templateUrl: x-template.html.
If I do <my-directive type="Y">
I want the directive to use templateUrl: y-template.html.
这是我当前的指令.
app.directive('myDirective', function() {
var myDirective = {
templateUrl: 'X-template.html',
restrict: 'E',
scope: {
type: '='
},
};
return myDirective;
});
我通读了 stackoverflow 和 angular 文档,但没有找到我需要的任何内容.
I read thru stackoverflow and angular documentation but have not found anything that I need.
我现在正在尝试做一些事情:
I am now trying to do something along the lines of:
if ($scope.type === 'X') {
templateUrl: 'X-template.html',
}
else if ($scope.type === 'Y') {
templateUrl: 'Y-template.html',
}
但是不知道在哪里做.
你们知道这是否可能以及如何实现吗?
Do you guys know if this is possible and how?
推荐答案
你可以解决 这个问题在compile
中使用ng-include
:
You can work around this issue using ng-include
inside compile
:
app.directive('myDirective', function() {
return {
restrict: 'E',
compile: function(element, attrs) {
element.append('<div ng-include="\'' + attrs.type + '-template.html\'"></div>');
}
}
});
这篇关于Angular 指令不同的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!