【发布时间】:2017-05-14 05:41:35
【问题描述】:
我的问题是:当父控制器中的变量值发生变化时,是否可以更改组件模板? 这里有两种我尝试遵循的方法:
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的值发生变化时,是否可以改变这个组件的模板呢?感谢您的帮助。
【问题讨论】:
-
您需要让父控制器将值传递给组件,我只需使用模板指令如
ng-if、ng-show、ng-hide等来更改组件 -
ng-if指令是最好的例子。要动态更改 HTML,需要取消注册观察者,需要销毁作用域,新 HTML 需要新作用域,并且需要编译和链接指令。要查看它是如何完成的:ng-if source code。或者只使用ng-if directive。 -
@theaccordance 谢谢你的回答
-
@georgeawg 也谢谢你
标签: angularjs components angular-components