SeriousJelly SeriousJelly - 4 months ago 9
AngularJS Question

Field name to form part of object used in ng-messages

I have a form where the fields are generated dynamically, here is an example field:

<input ng-required="!question.answers[questionKey]" type="radio" ng-model="question.answers[questionKey]" value="{{ option.value }}" name="question-{{ question.id }}" />


As you can see I am giving my field the name of
question-{{ question.id }}
this should give the value of question-1, question-2 etc.

I am now attempting to add some form validation to this field, how would access the property 'questionForm.question-1.$invalid' if the question-1 is dynamic?

Can I inject that into the following ng-messages directive somehow?

<div ng-messages="questionForm.name.$error">
<p ng-message="minlength">Your name is too short.</p>
<p ng-message="maxlength">Your name is too long.</p>
<p ng-message="required">Your name is required.</p>
</div>


I hope that I am making sense?

Answer

questionForm is an object so you can access his properties like this questionForm[question.id] and get the errors for each question dynamically.

<div ng-messages="questionForm[question.id].$error">
    <p ng-message="minlength">Your name is too short.</p>
    <p ng-message="maxlength">Your name is too long.</p>
    <p ng-message="required">Your name is required.</p>
</div>