我决定创建像单独的小部件一样的组件,例如父级将配置传递给它,组件获取数据(父级不需要子级的数据)。但是在某些情况下,例如父级中的一些更新,可能会影响显示的数据。所以我想对 child 说:重新获取数据,同时配置保持不变。但这不会导致触发 $onChanges
回调,因为配置对象的链接是相同的,所以我以一种 hacky 的方式修复了它:
vm.childConfig = _.assign({}, vm.childConfig);
这对我来说很好,但很丑。有没有更好的解决方案? (创建 $watch,发出事件似乎是更糟糕的解决方案)
一些示例代码:
<parent-component>
<child-component config="childConfig"></child-component>
</parent-component>
JS:
function ParentComponentController () {
vm.childConfig = {show: true, ...}
vm.onItemDelete = function () {
vm.childConfig = _.assign({}, vm.childConfig); // I want to call `fetchData` so I force child $onChanges to fire.
}
}
function ChildComponentController () {
vm.$onInit = function () {
fetchData()
}
vm.$onChanges = function () {
// will not fire if will not change the config object reference
fetchData(changes)
}
}
所以我想要类似 force child 调用 $onChanges
附言我不喜欢让子组件成为dumb组件(父组件将获取的数据传递给它)的想法,当然它会解决这个问题,但数据只在子组件中需要,它会让父组件变得更胖。
最佳答案
这就是你的意思吗?
JS
angular.module("app")
.component(
"ChildComponent",
{
controller: ChildComponentCtrl,
bindings: {
config: "<",
update: "<"
}
}
);
function ChildComponent () {
var init = false;
function init() {
// Set up config
init = true;
}
function update() {
// config remains the same but do something else
}
this.$onChanges = function () {
if (angular.isDefined(this.config) && !init) {
init();
}
else if (angular.isDefined(this.update)) {
update();
}
};
}
标记
<parent-component>
<child-component config="childConfig" update="update"></child-component>
</parent-component>
编辑 - 要确保更新不止一次有效,请执行以下操作:
子组件
this.$onChanges = function () {
if (angular.isDefined(this.config) && !init) {
init();
}
else if (angular.isDefined(this.update) && update) {
update();
}
};
父组件
function doUpdate() {
this.update = true;
// Rest update so that it works next time
$timeout(function () {
this.update = false;
});
}
关于javascript - Angular 1.5 组件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39389675/