对 AngularJS 个组件使用继承

Using Inheritance with AngularJS Components

我正在使用 AngularJS 组件,期待最终迁移到 Angular2。我有一个组件 (Component1),它本质上是一个带有一些特定输入和输出的下拉列表。我有另一个组件 (Component2),它是完全相同类型的下拉列表,但依赖于 Component1 中的 ng-model。有没有办法在 Component2 中使用继承,这样我就没有一堆重复的代码?

我可以在 Angular2 中看到如何使用继承,所以这似乎是最好的方法。但是,我在 Angular 1.5 中找不到任何说明如何执行此操作的内容。

Component1 也需要一个模板,但 Component1 和 Component2 的模板是一样的。此外,Component2 将需要来自 Component1 的值的额外输入,以及当该额外输入发生变化时 $onChanges 事件中的一些代码。

提前致谢!!

您能做的最好的事情就是将模型对象作为绑定传递给组件 2,

 app..component('component2', {
  bindings: {
    modelObject: '<'
  },
  controller: function () {
    //do stuff
  }
});

里面html

 <component2 model-object="$ctrl.modalObject"></component2>

当 component1 发生变化时。如果您的组件依赖于该更改 你需要使用 onchanges 生命周期钩子 components.inside component2 controller

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}
}
}