Angular dynamically set ng-messages to name attribute
Asked Answered
H

1

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?

Hoffarth answered 16/7, 2015 at 14:5 Comment(5)
Yes i got error, i cant send the ng-messages attribute with {{}} syntax, "Error: [$parse:syntax] Syntax Error: Token '{' is an unexpected token at column 13 of the expression [form.subName{{index}}.$error] starting at [{{index}}.$error]"Hoffarth
thats pretty weird cause i can set this on name attribute on input but can't on ng-messages :/Hoffarth
this piece of code is inside an ng-repeat??Depart
yes its inside ng-repeatHoffarth
this is your problem #12044777Depart
G
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>
Genotype answered 21/7, 2015 at 16:32 Comment(4)
Thank you for this, was having the same issue and it worked for me. Can you explain more on why form[] exists?Pitt
"form" is the name on the form so <form name="form"...> you could also do <form name="myForm"...> and the ng-messages directive would look like this ng-message="myForm['subName'...]. This works and should be the accepted answerCaulicle
This code only works for me when I changed ng-show="form.Name.$touched" to ng-show="form['subName' + $index].$touched"Hypostasize
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.Heterothallic

© 2022 - 2024 — McMap. All rights reserved.