我正在构建一个带有组件的站点导航,它是这样的:
<site-wrapper>
<site-header>
<site-menu />
</site-header>
<site-section />
<site-section />
</site-wrapper>现在,我的site-wrapper是这样的:
class siteWrapperController {
$onInit() {
this.sections = [];
}
addSection(section) {
if (this.sections.indexOf(section) === -1) {
this.sections.push(section);
}
}
}
app.component('siteWrapper', {
controller: siteWrapperController,
template,
transclude: true
});还有我的site-section
class siteSectionController {
$onInit() {
const id = this.sectionId;
const title = this.sectionTitle;
this.o = { id, title };
this.wrap.addSection(this.o);
}
}
app.component('siteSection', {
template,
transclude: true,
controller: siteSectionController,
bindings: {
sectionTitle: '@',
sectionId: '@'
},
require: {
wrap: '^siteWrapper'
}
});我在这里所做的基本上就是在sections数组中注册wrapper中的每个部分。现在我想把这个sections传递给site-menu
class siteMenuController {
$onInit() {
this.buildSections(this.wrap.sections);
}
buildSections(sections) {
Array.prototype.forEach.call(sections, s => {
console.log(s);
});
}
}
app.component('siteMenu', {
controller: siteMenuController,
bindings: {
items: '<',
className: '@'
},
template: template,
transclude: true,
require: {
wrap: '^siteWrapper'
}
});不幸的是,它返回空。这意味着,这运行得太早了。我可以直接把setTimeout放在那里,然后就完事了,但我相信还有更好的方法。我希望省略$scope和$broadcast/$emit,而只是让组件以某种方式相互通信;-)
我能做什么?
发布于 2016-06-17 19:50:38
您可以监视变量,该变量将在变量的值发生变化时执行
例如,如果您的变量为$scope.newVar
然后你可以把watcher放在上面
$scope.$watch('newVar',function(newval,oldval){
//your code goes here
})https://stackoverflow.com/questions/37880420
复制相似问题