Darius Buhai
Darius Buhai

Reputation: 61

How to use $index in ng-if

So I have this code below

<form name="registrationForm">
<div class="form-inline" ng-repeat="participant in participantsArray">
        <div class="form-group">
          <input ng-model="datas.name[$index+1]" name="name{{$index+1}}" required verify-name>
          <span ng-if="registrationForm.name+($index+1).$dirty && registrationForm.name+($index+1).$invalid">error</span>
        </div>
</div>
</form>

and is not working, how do I need to use the $index expression in the ng-if? the ng-model, and the name are working properly ...

Upvotes: 0

Views: 6324

Answers (3)

Anil Yadav
Anil Yadav

Reputation: 1096

Try this :)

<span ng-if="registrationForm['name'+($index+1)].$dirty && registrationForm.name+($index+1).$invalid">error</span>

Upvotes: 1

Manish
Manish

Reputation: 5066

I ran into a same problem once. What you can do is instead of dot(.) notation use bracket notation to access the form controls. Thats what worked for me. Below is a example. Try this this will work. Let know if you need help.

registrationForm['name'+($index+1)].$dirty

Hope it Helps :)

Upvotes: 2

Pengyy
Pengyy

Reputation: 38171

For dynamic fields you can use [] to wrap the dynamic string field.

registrationForm['name'+($index+1)].$dirty

refer the below example:

angular.module("app", [])
  .controller("myCtrl", function($scope) {
    $scope.items = ['a','b','c','d'];
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <form name="registrationForm">
    <div ng-repeat="item in items">
      <input ng-model="datas.name[$index+1]" name="name{{$index+1}}" required verify-name>
      <span ng-if="registrationForm['name'+($index+1)].$dirty && registrationForm['name'+($index+1)].$invalid">error</span>
    </div>
  </form>
</div>

Upvotes: 5

Related Questions