我的问题是:当父 Controller 中变量的值发生变化时,是否可以更改组件模板? 我尝试遵循以下两种方法:
var topBarTemplateWithButton = [
'<section id="filters">',
'<div class="pull-left">',
'<h1>{{$ctrl.step}}</h1>',
'<div class="pull-left pageActionContainer">',
'<ng-transclude></ng-transclude>',
'</div>',
'</div>',
'</section>'].join(' ')
var topBarTemplateWithoutButton = [
'<section id="filters">',
'<div class="pull-left">',
'<h1>{{$ctrl.step}}</h1>',
'</div>',
'</section>'].join(' ')
myApp.component('topBar', {
bindings: {
step: '<'
},
template: this.templateToUse,
transclude: true,
controller: function() {
var me = this;
me.$onInit = function() {
this.templateToUse = topBarTemplateWithButton;
}
me.$onChanges = function(changes) {
if(changes.step.currentValue != "Projects") {
this.templateToUse = this.topBarTemplateWithoutButton;
}else {
this.templateToUse = topBarTemplateWithButton;
}
}
}
});
和
var topBarTemplateWithButton = [
'<section id="filters">',
'<div class="pull-left">',
'<h1>{{$ctrl.step}}</h1>',
'<div class="pull-left pageActionContainer">',
'<ng-transclude></ng-transclude>',
'</div>',
'</div>',
'</section>'].join(' ')
var topBarTemplateWithoutButton = [
'<section id="filters">',
'<div class="pull-left">',
'<h1>{{$ctrl.step}}</h1>',
'</div>',
'</section>'].join(' ')
myApp.component('topBar', {
bindings: {
step: '<'
},
template: '<div ng-include="$ctrl.templateToUse"/>,
transclude: true,
controller: function() {
var me = this;
me.$onInit = function() {
this.templateToUse = topBarTemplateWithButton;
}
me.$onChanges = function(changes) {
if(changes.step.currentValue != "Projects") {;
this.templateToUse = this.topBarTemplateWithoutButton;
}else {
this.templateToUse = topBarTemplateWithButton;
}
}
}
});
这两个例子都不起作用。那么当step
的值改变时,可以改变这个组件的模板吗?感谢您的帮助。
最佳答案
Template
字段可以是返回模板的函数,并且它将 attrs
作为可注入(inject)的。这是一个可能实现您正在寻找的内容的示例。
template: function(attrs) {
"ngInject";
// check for custom attribute and return different template if it's there
},
但是,重要的一点是,这些属性此时未编译,因为模板尚未编译。事实上,在确定模板之前它无法被编译。因此您检查的它们属性只能是字符串文字..
关于angularjs - Angular : Change component template using variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41387468/