24

How do I name a form inside ng-repeat with a dynamic name?

<div ng-repeat="item in itemList">
 <form name="item_details" ng-class="validateForm(item_details)">
   //few form elements
 </form>
</div>

I want to name each form dynamically. For example add the $index to the name of the form. How do I achieve it? I tried ng-init on ng-repeat but did not work.

suman j
  • 6,140
  • 10
  • 51
  • 99

2 Answers2

21

You can just do:

<form name="item_details{{$index}}" ng-class="validateForm('item_details'+$index)">

EDIT:

You can use ng-init as well, like so:

<div ng-repeat="item in itemList" ng-init="formName = 'item_details' + $index">
 <form name="{{formName}}" ng-class="validateForm(formName)">
   //few form elements
 </form>
</div>

If it's just to apply a class based on validity of the form, then you could apply styling to automatically added classes, such as: ng-valid:

.ng-valid {
   background-color: green;
}
New Dev
  • 46,536
  • 12
  • 79
  • 122
  • 1
    This didnt work. `
    ` validateForm method received undefined for form variable input.
    – suman j Dec 16 '14 at 20:39
  • You missed my point. You don't need the `validateFrom` if all you need to do is to style the CSS – New Dev Dec 16 '14 at 20:43
  • its a complex validation and not css change. Multiple form fields values are validated to enable the submit button. – suman j Dec 16 '14 at 20:44
  • 1
    with this case, validateForm method does not receive the form controller instance. Instead its input becomes "String" object with form name – suman j Dec 17 '14 at 00:05
  • can you please define `validateForm(formName)` this function – Yougesh Jun 01 '17 at 06:58
2

You may access the instance of the form by the dynamic name using bracket notation:

<div ng-repeat="item in itemList">
  <form name="item_details{{$index}}" ng-class="validateForm(this['item_details' + $index])">
    //few form elements
  </form>
</div>
Todd Hirsh
  • 41
  • 2
  • 4