Gustavo Vieira Gustavo Vieira -4 years ago 87
AngularJS Question

$index in ng-class for form validation

I want to validate an angular form input and give it a class if is not $valid, the problem is, it´s inside a ng-repeat looping an array of int, and the input name is based on the $index:

<li ng-repeat="item in selectedItem.data.ax_ch">
<div ng-class="{'has-error':!form.ax_$index.$valid}">
<input type="text" id="ax_{{$index}}" name="ax_{{$index}}" ng-model="item" required=""/>
</div>
</li>


Everything gets the $index in the output, but the ng-class:

<li ng-repeat="item in selectedItem.data.ax_ch">
<div ng-class="{'has-error':!form.ax_$index.$valid}">
<input type="text" id="ax_0" name="ax_0" ng-model="item" required=""/>
</div>
</li>


What I expected it to be:

<li ng-repeat="item in selectedItem.data.ax_ch">
<div ng-class="{'has-error':!form.ax_0.$valid}">
<input type="text" id="ax_0" name="ax_0" ng-model="item" required=""/>
</div>
</li>


I have searched and people have similar problems but none of them have been solved so far. Is there any angular-super-hero-master-plus-advanced who can help me with it :) ?

Answer Source

Because you are constructing the property/key on form dynamically, you do the same thing you would in normal Javascript: use square["bracket"] notation.

Change your markup to:

<li ng-repeat="item in selectedItem.data.ax_ch">
  <div ng-class="{'has-error':!form['ax_' + $index].$valid}">
     <input type="text" id="ax_{{$index}}" name="ax_{{$index}}" ng-model="item" required=""/>
  </div>
</li>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download