How to get the parent form of a from a custom form control directive in angular?


Usually, validating forms in angular is done like this:

<form name="form">
  <input name="fruit" ng-model="ctrl.fruit" required>
  <span class="error" ng-show="form.fruit.$error.required">
    Fruit is required.

The thing is that I have multiple forms some of which have similar fields, so I want to refactor some of this logic into a directive:

<form name="form1">

<form name="form2">

The problem is that the logic to display or hide the field error message requires the template to have access to the form to evaluate the condition form.fruit.$error.required. But my fruitInput directive needs to work regardless of the form where it's inserted.

Is there a way for the directive to identify its parent form so I can use it in its (isolated) scope to show/hide the error message?

Edit (due to a response questioning the usefulness of the question): Evidently the example is simplified.

In reality, a field on the form may have many of the following: a label, a help text, tooltip on hover, links to documentation, the control itself, all the different validation messages for the different validation conditions. One of such controls can easily be 20 lines of code and be used in 4~5 different places. So it's worth refactoring it.

Problem courtesy of: Juan Enrique Muñoz Zolotoochin


Try this directive:

  return {
    template:'<input name="fruit" ng-model="ctrl.fruit" required> ' +
     ' <span class="error" ng-show="form.fruit.$error.required"> ' + //form here is the parent form resolved dynamically and saved in the scope as a property
     '  Fruit is required. ' +
     ' </span>',
     require:"^form", //inject parent form as the forth parameter to the link function
     link:function (scope,element,attrs,form){
       scope.form = form; //save parent form


Solution courtesy of: Khanh TO


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.