5

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?

Danny
  • 7,368
  • 8
  • 46
  • 70

2 Answers2

5

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> 
aet
  • 7,192
  • 3
  • 27
  • 25
  • 1
    There is actually an [issue open for AngularJS](https://github.com/angular/angular.js/issues/1404), where one of the comments has a [workaround](https://github.com/angular/angular.js/issues/1404#issuecomment-30861993). This worked a lot better for my setup. – Danny Apr 24 '14 at 14:58
  • 2
    For anyone else that comes across this, the issue is closed and name can now be dynamically generated. – John R Jan 12 '15 at 04:41
0

Using at least AngularJS 1.4.3 you can use this:

name="formControl_{{uniqueId}}"

And this:

ng-messages="myForm[ 'formControl_' + uniqueId ].$error"

Taken from the comment at https://github.com/angular/angular.js/issues/1404#issuecomment-125805732 found in the issue referenced by Danny.

DavidC
  • 654
  • 1
  • 14
  • 20