Reputation: 3579
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.
</span>
</form>
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">
<fruit-input></fruit-input>
</form>
<form name="form2">
<fruit-input></fruit-input>
</form>
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.
Upvotes: 3
Views: 7002
Reputation: 48972
Try this directive:
app.directive("fruitInput",function(){
return {
restrict:"E",
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>',
scope:{},
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
}
}
})
Upvotes: 10