Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  58] [ 4]  / answers: 1 / hits: 6955  / 10 Years ago, sat, april 26, 2014, 12:00:00

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.


More From » angularjs

 Answers
10

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


DEMO


[#45744] Thursday, April 24, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
clarkulisesa

Total Points: 422
Total Questions: 93
Total Answers: 112

Location: Austria
Member since Thu, Jan 7, 2021
3 Years ago
clarkulisesa questions
Mon, Feb 24, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;