【发布时间】:2017-08-25 16:22:23
【问题描述】:
我的组件将一个对象作为绑定传递,
.component('selectionButton', {
bindings: {
parentForm : '<'
},
templateUrl: 'selection-button-component.html',
controller: 'selectionButtonController',
controllerAs: 'selBtnCtrl'
});
问题是当我的组件初始化时我传递的对象还没有加载,所以在 $onChanges 钩子中我这样做了:
vm.$onChanges = function(newObj){
if(angular.isDefined(newObj.parentForm.currentValue)){
vm.parentForm = newObj.parentForm.currentValue;
}
};
在我的控制器中,我在一个函数中调用vm.parentForm,当我在页面完全加载后单击按钮时触发该函数,但我总是将它作为undefined,即使我使用@987654325 更改了它的值@。
当我检查vm.$onChanges 函数时,我可以看到vm.parentForm 的值正在changesObj.parentForm 中获取新值。
我该如何解决这个问题?
编辑:
我尝试用ng-if 包装我的元素,如下所示:
<span ng-if="fullPage.posteForm">
<selection-button parent-form="fullPage.posteForm" ></selection-button>
</span>
但这没有用。我还尝试了双向绑定,但效果不佳。
【问题讨论】:
-
两种可能的解决方案。 1.将绑定更改为=。 2. 有一个 ng-if="vm.parentForm" 来包装 html,所以一旦它被初始化,html 将重新编译。
-
你根本不需要 ng-if 来解决这个问题:在你的子组件中使用 onChanges 所以每次你的值将被更新时,钩子 onChanges 将在子组件内触发,所以你可以分配新的对象值。
onChanges() = function(changes) { if (changes.parentForm.currentValue !== undefined) { this.parentForm = changes.parentForm.currentValue; } -
您实际上不必更新组件的本地范围,因为它会在任何绑定更改时自动更新。
-
你能分享你剩下的控制器代码吗?也许问题根本不在于绑定。
-
制作小提琴/plunk - 你在这里的所有东西都可以工作
标签: angularjs angularjs-components