Search code examples
angularjsangularjs-ng-repeatng-class

Conditionally add a class to dynamically generated fields


I'm making some sort of validation using ng-class directive, but there's a problem when starting to deal with ng-repeat created elements.

<div class="traveler" ng-repeat="i in getNumber(travelers_count) track by $index" style="margin-top: 15px">
                        <div class="inp-wr wr-traveler">
                            <input
                                ng-class="{ 'has-error' : valError && mainForm.last_name[{{$index + 1}}].$invalid}"
                                required
                                class="text-inp"
                                style="width: 200px"
                                ng-model="$parent.last_name[$index]"
                                ng-model-options="{ updateOn: 'blur' }"
                                ng-pattern="namePattern"
                                name="last_name[{{$index + 1}}]"
                                placeholder = "Last name">
                        </div>
</div>

Is there a way to make this one work? ng-class="{ 'has-error' : valError && mainForm.last_name[{{$index + 1}}].$invalid}"


Solution

  • Found quick solution - need to wrap input in <ng-form> and check validity of it. I.e

    <div class="traveler" ng-repeat="i in getNumber(travelers_count) track by $index" style="margin-top: 15px">
                                <div class="inp-wr wr-traveler">
    <ng-form name="lastNameForm">
                                    <input
                                        ng-class="{ 'has-error' : valError && lastNameForm.$invalid}"
                                        required
                                        class="text-inp"
                                        style="width: 200px"
                                        ng-model="$parent.last_name[$index]"
                                        ng-model-options="{ updateOn: 'blur' }"
                                        ng-pattern="namePattern"
                                        name="last_name[{{$index + 1}}]"
                                        placeholder = "Last name">
    </ng-form>
                                </div>
        </div>