Search code examples
javascriptangularjsformsangularjs-ng-repeatng-class

ng-class in ng-repeat with a $index selector


I want to select in the ng-class the form element, which is inside a ng-repeat, i need a 1:n selector in the ng-class. But the {{}} + $index is working correctly in the ng-class expression. The sector is parsed correct. But ng-class can not handle it. It is no detecting the selector, when {{}} + $index is inside.

Code:

<form name="vm.itemForm" ng-submit="vm.onSave()">
(...)
  <tr ng-repeat="item in vm.item.sizes | orderBy:predicate:reverse">
    (...)
     <div class="dc-input-group">
        <input class=""
               ng-model="item.stock"
               ng-class="{ 'testclass': vm.itemform.{{'stockInput'+$index}}.mySelector  }" 
               name="{{'stockInput'+$index}}" />
        </div>

HTML Output:

  <input class="form-validation dc-input dc-input--in-input-group dc-input--text-right ng-touched ng-not-empty ng-dirty ng-valid-number ng-valid ng-valid-required" 
    ng-model="item.stock"
    ng-class="{ 'testclass': vm.form.stockInput1.$valid }" 
    required=""
    name="stockInput1" 
    type="number"> 

Solution

  • The ng-class is already an expression, so you were putting 2 expressions inside eachother. You can fix it like this:

    <input class=""
           ng-model="item.stock"
           ng-class="{'testclass': vm.itemform['stockInput'+$index].mySelector}" 
           name="{{'stockInput'+$index}}" />