Skip to content

Instantly share code, notes, and snippets.

@lund0n
Created December 8, 2014 20:30
Show Gist options
  • Save lund0n/31cc7240d00ec4dc4821 to your computer and use it in GitHub Desktop.
Save lund0n/31cc7240d00ec4dc4821 to your computer and use it in GitHub Desktop.
ng-form: Nesting Forms for Repeating Inputs
<div ng-app="demo" ng-controller="Demo as vm">
<form name="example">
<div>
<label>Your name:
<input type="text" name="name" ng-model="vm.name" required/>
<span ng-show="example.name.$invalid">invalid!</span>
</label>
</div>
<div>Name your three favorite ice cream flavors:</div>
<ul>
<li ng-repeat="flavor in vm.flavors">
<input type="text" name="flavor" ng-model="flavor" required />
<span ng-show="example.flavor.$invalid">invalid!</span>
</li>
</ul>
</form>
</div>

ng-form: Nesting Forms for Repeating Inputs

ngModel's validation state properties don't work nicely when you have repeating inputs, as later input validation states in the repeat override ones earlier in the repeating block. The trick is to use a nested form (ng-form) to treat each repeating element as its own form. That works with the root form as well as allows you to put error messages in correctly.

To fix the error messages on the repeating element:

  1. Add a ng-form="flavors" to the li element.
  2. Change the ng-show to flavors.flavor.$invalid.

A Pen by Jeremy Lund on CodePen.

License.

function Demo() {
this.name = 'John Doe';
this.flavors = ['chocolate', 'strawberry', 'vanilla'];
}
angular.module('demo', []).controller('Demo', Demo);
form, div, li {
margin: 10px;
}
form.ng-valid, input.ng-valid {
border: solid 2px #090;
background: #efe;
}
form.ng-invalid {
border: solid 2px #900;
}
input.ng-invalid {
border: solid 2px #900;
background: #f33;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment