Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the child ngModel from a directive?

Like in this question, I want to add .error on a form field's parent .control-group when scope.$invalid is true.

However, hardcoding the form name like in ng-class="{ error: formName.fieldModel.$invalid }" means that I can't reuse this in different forms, plus I'd rather not repeat this declaration everywhere.

I figured that a directive that looks something like this could work:

<div class="control-group" error-on="model1, model2">
  <input ng-model="model1">
  <input ng-model="model2">
</div>

So when either model1 or model2 is not valid, .control-group gets .error added.

My attempt here. Is it possible to access the models from the directive, given the model names?

If there's a better approach, I'd love to hear it too.

like image 260
thatmarvin Avatar asked Apr 20 '13 01:04

thatmarvin


1 Answers

I don't think that writing a custom directive is necessery for this use-case as the ng-form directive was created exactly for situations like those. From the directive's documentation:

It is useful to nest forms, for example if the validity of a sub-group of controls needs to be determined.

Taking your code as an example one would write:

<div class="control-group" ng-class="{ error: myControlGroup1.$invalid }>
  <ng-form name="myControlGroup1">
    <input ng-model="model1">
    <input ng-model="model2">
  </ng-form>
</div>

By using this technique you don't need to repeat expressions used in ng-model and can reuse this fragment inside any form.

like image 176
pkozlowski.opensource Avatar answered Oct 05 '22 00:10

pkozlowski.opensource