简体   繁体   中英

How to reference child controllers of a certain type from an angular directive or component?

When I define an angular component or directive, I can use 'require' to bind to a parent controller like require: {'parentForm' : '^^ngForm'} .

I'd like to do the same thing, but in reverse: require: {'childrenForms' : '[children]ngForm'} would bind childrenForms to an array of all controllers contained within my component which are ngForms.

I want to do this in order to build components that add aggregate behavior to directives I don't have control over. For example my-special-form container could have an isValid() method that returns true if all the ng-forms within it are valid at the moment.

Is there any way to do this? Am I making a mistake by even wanting to?

There is no option to require inner child directive in Angular. Personally I don't think so the approach you thought about would be good approach to go for, like here parent directive want to know directly about child directive. Rather I'd say choose the approach where child directive will pass required data to parent controller by calling one of its method.

If you only wanted to validate inner forms then you can wrap all the inner forms inside wrapper form ng-form with some name(you can have nested form in angular using ng-form directive). You can see example below, where you can see I wrapped all the inner form with one wrapper form element ng-form . So what happen is, when any one of the forms get invalid the parent form will invalid. If all forms are valid then parentForm will become valid as well.

Markup

{{parentForm.$valid}}
<div ng-form name="parentForm" my-directive>
   <form name="form1" some-directive>
     .....
   </form>
   <form name="form2" some-directive>
     .....
   </form>
   <form name="form3" some-directive>
     .....
   </form>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM