madhu madhu - 3 months ago 24
AngularJS Question

angular validation within ng-repeat

I have below validation for my texboxes within ng-repeat

<div class="col-md-6 col-lg-2">
<div class="form-group">
<label for="Country{{$index}}" class="control-label required">Country</label>
<div class="input-group">
<mc-lookup-dropdown data-lookup-name="CountryType" required data-model="ContactAddress.Country" id="Country{{$index}}" name="Country{{$index}}" class="form-control"></mc-lookup-dropdown>
</div>
<div data-ng-messages="memberDemographics.demographics.$error" class="validation-errors">
<div data-ng-message="Country">{{ ContactAddress.$serverErrors.Country }}</div></div>
<div data-ng-messages="demographicsForm.{{'Country'+$index}}.$error" class="validation-errors">
<div data-ng-message="required" data-ng-show="!demographicsForm.{{'Country'+$index}}.$pristine">This Field is Required</div>
</div>
</div>
</div>


below error is thrown on pageload "rror: [$parse:syntax]


http://errors.angularjs.org/1.5.8/$parse/syntax?p0=%7B&p1=is%20not%20a%20validNaNdentifier&p2=18&p3=demographicsForm.%7B%7B'PhoneNumber'%2B%index%7D%7D.%24error&p4=%7B%7B'PhoneNumber'%2B%index%7D%7D.%24error"


i need to have expression with in ng-message since textname depends on $index of ng-repeat loop..

Answer

These lines are having errors:

<div data-ng-messages="demographicsForm.{{'Country'+$index}}.$error" class="validation-errors">
<div data-ng-message="required" data-ng-show="!demographicsForm.{{'Country'+$index}}.$pristine">This Field is Required</div>

Change this with :

<div data-ng-messages="demographicsForm['Country' + $index].$error" class="validation-errors">
<div data-ng-message="required" data-ng-show="!demographicsForm['Country'+$index].$pristine">This Field is Required</div>

From this article

You only need to wrap in braces when using Angular's templating system - the braces tell Angular to replace the value. In this case, the value of data-ng-message is an expression that is being evaluated.

Comments