29

I dynamically create inputs and want also validate every one of them but can't set correctly the ng-messages attribute to the field name property which is dynamically generated.

<input ng-model="sub.name" name="subName{{$index}}" class="form-control" placeholder="name" required maxlength="20" />
<div class="field-error" ng-messages="form.subName{{$index}}.$error" ng-show="form.Name.$touched" role="alert">
    <div ng-message="required">Name is required.</div>
</div>

I got problem with second line where I set the ng-messages dynamically to ng-messages. How can I do this?

Dale K
  • 25,246
  • 15
  • 42
  • 71
CSharpBeginner
  • 1,625
  • 5
  • 22
  • 36

1 Answers1

57

Accessing the properties of your form object can also be done using brackets, which should solve your problem :

<input ng-model="sub.name" name="subName{{$index}}" class="form-control" placeholder="name" required maxlength="20" />
<div class="field-error" ng-messages="form['subName' + $index].$error" ng-show="form.Name.$touched" role="alert">
    <div ng-message="required">Name is required.</div>
</div>
Helori
  • 571
  • 3
  • 2
  • Thank you for this, was having the same issue and it worked for me. Can you explain more on why form[] exists? – tchen Aug 07 '15 at 16:10
  • 1
    "form" is the name on the form so
    you could also do
    and the ng-messages directive would look like this ng-message="myForm['subName'...]. This works and should be the accepted answer
    – SomethingOn Sep 28 '15 at 18:16
  • This code only works for me when I changed ng-show="form.Name.$touched" to ng-show="form['subName' + $index].$touched" – Alex Coroza Nov 08 '15 at 06:14
  • Thanks this information really helped me, was using ng-messages but my input field had a name in the format "firstpart.secondpart" which angular couldnt understand. However using form['firstpart.secondpart'].$error fixed the problem. Thanks. – RollingInTheDeep Feb 09 '18 at 11:04