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?

2 Answers 2

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> 
Sign up to request clarification or add additional context in comments.

2 Comments

There is actually an issue open for AngularJS, where one of the comments has a workaround. This worked a lot better for my setup.
For anyone else that comes across this, the issue is closed and name can now be dynamically generated.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.