1

I am iterating over a array of strings with ng-repeat

<div ng-repeat="i in mdsecuritysensorswsize">

in there I have a required select with a 'dynamic model'

ng-model="valueBag[i+'sizes']"

now I want to add a has-error class, if the select is empty (apply bootsrap3 error style)

ng-class="{'has-error': myForm.valueBag[i+'sizes'].$invalid, 'has-success': !myForm.valueBag[i+'sizes'].$invalid}"

But this doesn't seem to work with such a dynamic ng-model name.

Here is the complete code:

<div ng-repeat="i in mdsecuritysensorswsize">
  <div class="form-group">
    <div class="col-md-2"
         ng-class="{'has-error': myForm.valueBag[i+'sizes'].$invalid, 'has-success': !myForm.valueBag[i+'sizes'].$invalid}"
         >
      <select class="form-control" required
          ng-options="resText[j] for j in mdsecuritysensorswsizesizes2"
          ng-model="valueBag[i+'sizes']"></select>
     </div>
   </div>
</div>

Am I missing something here?

Daniel Kreiseder
  • 12,135
  • 9
  • 38
  • 59
  • try using `$index` instead of `i` to access you array elements, have a look at [this answer](http://stackoverflow.com/a/21414140/189756) – Mohammad Sepahvand Feb 03 '14 at 08:37
  • Please post the code of the controller. – Michał Miszczyszyn Feb 03 '14 at 08:38
  • 2
    if you create your form inputs dynamically, it will be a problem with this code when you try to access `myForm.valueBag[i+'sizes'].$invalid` If you create form inputs dynamically, check out my directive to solve this problem here: http://stackoverflow.com/questions/21455695/angularjs-dynamic-form-field-validation/21457121#21457121 – Khanh TO Feb 03 '14 at 10:04

1 Answers1

2

this from the comments did the job:

if you create your form inputs dynamically, it will be a problem with this code when you try to access myForm.valueBag[i+'sizes'].$invalid If you create form inputs dynamically, check out my directive to solve this problem here: stackoverflow.com/questions/21455695/… – Khanh TO Feb 3 at 10:04

AngularJS dynamic form field validation

THX @Khanh TO

Community
  • 1
  • 1
Daniel Kreiseder
  • 12,135
  • 9
  • 38
  • 59