www www - 26 days ago 14
AngularJS Question

Angular ng-messages inside custom directive inside ng-repeat wrong behaviour

I have same problem as described in this toppic:
Angular JS ng-message inside directive

Unfortunatelly that solutions is not working for me, because I am using my custom directive inside ng-repeat. So now ng-messages work only when error condition is fulfilled for all inputs.

http://plnkr.co/edit/lJT48bmYvR9DGFliIYDH?p=preview

I have tried many ways for creating ng-messages condition but nothing worked properly. Two of them You can find in above plunker:

ng-messages="form.doubleInputLeft.$error"
ng-messages="form['doubleInputRight' + $index].$error"


Please help me,
Regards

Answer

For input elements to work inside an ng-repeat, the index must be included as part of the name attribute.

    <!-- index must be included in the name attribute --
    <input name="doubleInputLeft" class="form-control ngMessageSample" type="{{inputType}}"  ng-model="modelLeft" ng-minlength="2" ng-maxlength="20" required>
    -->
    <input name="doubleInputLeft{{index}}" class="form-control ngMessageSample" type="{{inputType}}"  ng-model="modelLeft" ng-minlength="2" ng-maxlength="20" required>
    <div ng-messages="form['doubleInputLeft'+index].$error" class="ngMessagesClass" ng-messages-multiple>
      <div ng-message="minlength" class="ngMessageClass"> {{leftInputHeading}} must have at least 2 characters.</div>
      <div ng-message="maxlength" class="ngMessageClass"> {{leftInputHeading}} must have at most 20 characters.</div>
    </div>

Otherwise, the repeated elements will have duplicate names.

The DEMO on PLNKR