【发布时间】:2018-04-10 06:47:46
【问题描述】:
app.directive("itemsContainer", function() {
return {
restrict: "E",
controllerAs: "itc",
bindToController: true,
controller: function() {
this.showItems = false;
this.items = null;
this.loadItems = (data) => {
this.items = data;
this.showItems = true;
}
this.hideSummary = () => {
this.showItems = false;
}
},
templateURL:'itemsContainer.html'
};
});
app.directive("itemsSummary", function() {
return {
restrict: "E",
require: "^itc",
link: function(scope, element, attrs, ctrl) {
scope.showSummary = ctrl.showItems;
scope.items = ctrl.items;
},
templateURL:'itemsSummary.html'
};
});
app.directive("itemsList", function() {
return {
restrict: "E",
require: "^itc",
scope: {
items = "="
},
link: function(scope, element, attrs, ctrl) {
if(items !== null)
{
ctrl.loadItems(items);
}
scope.hideSummary = () => {
ctrl.hideSummary();
}
},
templateURL:'itemsList.html'
};
});
<itemsContainer>
<itemsSummary>{{itemsSummary}}</itemsSummary>
<itemsList>{{items}}</itemsList>
</itemsContainer>
这里,当 itemsList 指令使用 itemsContainer 控制器设置隐藏摘要时,在 itemsSummary 中没有更新? 如何使所有三个指令同步? 兄弟指令之间沟通的最佳方式? 目前正在做我不想做的事件发射。 我需要一个最佳实践解决方案。
我的要求:
<parent>
<child1></child1>
<child2></child2>
</parent>
如何将 child2 中的任何更新传达给 child1?
【问题讨论】:
-
正如它所写的,这太宽泛了,考虑改写它以匹配一个唯一的问题。询问最佳实践可能更适合codereview.stackexchange.com
-
它不会更新
this.showItems变量或HTML?此外,如果它们是同级的,而不是嵌套的,则不能相互引用。 -
@SlavaUtesinov 是的,this.showItems 在摘要 html 中没有更新。怎么办?
-
@MoganRangan,尝试将其包装成:
scope.$apply(() => { this.showItems = false; }) -
这是指令与组件的完美示例。这些应该是嵌套组件
标签: angularjs angularjs-directive