【问题标题】:Using Inheritance with AngularJS Components在 AngularJS 组件中使用继承
【发布时间】:2016-07-26 20:10:58
【问题描述】:
我正在使用 AngularJS 组件,以期最终迁移到 Angular2。我有一个组件(Component1),它本质上是一个带有一些特定输入和输出的下拉列表。我有另一个组件(Component2),它是完全相同的下拉列表,但依赖于 Component1 中的 ng-model。有没有办法在 Component2 中使用继承,这样我就没有一堆重复的代码?
我可以看到如何在 Angular2 中使用继承,所以这似乎是最好的方法。但是,我找不到任何显示如何在 Angular 1.5 中执行此操作的内容。
Component1 也需要一个模板,但是对于 Component1 和 Component2 来说都是一样的。此外,Component2 将需要对来自 Component1 的值的附加输入,以及当附加输入更改时 $onChanges 事件中的一些代码。
提前致谢!!
【问题讨论】:
标签:
angularjs
inheritance
angularjs-components
【解决方案1】:
您能做的最好的事情是将模型对象作为绑定传递给组件 2,
app..component('component2', {
bindings: {
modelObject: '<'
},
controller: function () {
//do stuff
}
});
在html里面
<component2 model-object="$ctrl.modalObject"></component2>
当组件 1 发生变化时。如果您的组件依赖于该更改
你需要使用 onchanges 生命周期钩子 components.inside component2 控制器
this.$onChanges=function(data){
//this data has all changed values..
// you can also use isFirstChange() to determine if it was the first or not.
if(data.hasOwnProperty('modalObject'){
if(!data.modalObject.isFirstChange()){//means its not the initialization}
}
}