简体   繁体   中英

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 ...

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> 

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 :)

尝试这个 :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM