2

I am using AngularJS components in anticipation of eventually moving to Angular2. I have a component (Component1) that is essentially a dropdown with a few specific inputs and outputs. I have another component (Component2) that is the exact same kind of dropdown, but has a dependency on the ng-model in Component1. Is there a way to use inheritance in Component2 so that I do not have a bunch of duplicate code?

I can see how to use inheritance in Angular2, so this seems to be the best approach. However, I can't find anything showing how to do this in Angular 1.5.

Component1 also requires a template, but it will be the same for both Component1 and Component2. Also, Component2 will require an additional input for the value from Component1, as well as some code in the $onChanges event when that additional input changes.

Thanks in advance!!

4

1 回答 1

1

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

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

在html里面

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

当component1发生变化时。如果您的组件依赖于该更改,您需要使用 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}
}
}
于 2017-05-18T07:29:19.457 回答