Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS required field validation in ng-repeat

Tags:

angularjs

I am trying to follow the AngularJS example of doing inline validations of required fields. However when it comes to using a ng-repeat, it doesn't seem to work for me.

<form name="myForm" novalidate>
  Me: <input required type="text" name="myName" ng-model="name" />
  <span class="error" ng-show="myForm.myName.$error.required">Required!</span>
  <div ng-repeat="friend in friends">
      Friends: <input required type="text" name="myFriend[{{$index}}]" ng-model="friend.name" />
      <span class="error" ng-show="myForm.myFriend[{{$index}}].$error.required">Required</span>
  </div>
</form>

JSFiddle

Any idea what I am doing wrong or what I can do to fix it?

like image 309
Danny Avatar asked Apr 17 '14 19:04

Danny


1 Answers

Unfortunately you cannot do it that way. The input element does not like having the name dynamically generated. You will need to use ng-form as a subform and wrap the repeated element. Here is a fork of your fiddle: http://jsfiddle.net/p26VQ/

<div ng-controller="MyCtrl">
  <form name="myForm" novalidate>
      Me: <input required type="text" name="myName" ng-model="name" /><span class="error"  ng-show="myForm.myName.$error.required">
  Required!</span>
      <div ng-repeat="friend in friends">
          <ng-form name="subform{{$index}}">
              Friends: <input required type="text" name="myFriend" ng-model="friend.name" /> 
              <span class="error" ng-show="subform{{$index}}.myFriend.$error.required">Required</span>
          </ng-form>
      </div>
  </form>
</div> 
like image 81
aet Avatar answered Oct 02 '22 05:10

aet