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.

3
  • 4
    downvotes make no sense - it is a legitimate question Commented Feb 9, 2015 at 18:20
  • 3
    i agree that downvotes make no sense. Commented Mar 5, 2015 at 8:29
  • 1
    yes no reason to down vote, this is a legitimately difficult task that has generated legitimately helpful answers Commented Jun 15, 2015 at 6:35

2 Answers 2

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

5 Comments

This didnt work. <form name="item_details{{$index}}" ng-class="validateForm(item_details{{$index}})"> validateForm method received undefined for form variable input.
You missed my point. You don't need the validateFrom if all you need to do is to style the CSS
its a complex validation and not css change. Multiple form fields values are validated to enable the submit button.
with this case, validateForm method does not receive the form controller instance. Instead its input becomes "String" object with form name
can you please define validateForm(formName) this function
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>

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.