AngularJS validation referencing form object with variable name

Issue

Let’s say I have a simple form with some Angular validation:

<form name="myForm">
    <input name="{{myField}}" 
            type="text" 
            ng-model="obj.myField" 
            required />
    <div class="text-danger" ng-show="myForm[myField].$invalid">
        <div ng-show="myForm[myField].$error.required">
            Field is required.
        </div>
    </div>
</form>

Now let’s say I want to use a variable for the form name instead of a hard-coded string:

<form name="{{formName}}">

How can I modify myForm[myField].$invalid and myForm[myField].$error.required to still reference my form?

Solution

As of the current angular, you cannot have dynamically named form input elements. If you are doing this over a collection of forms, you can use the ng-form directive and do something like this (in jade syntax):

div(ng-repeat = "user in users", class="form-group")
    ng-form(name="userFieldForm")
      input(type="text", required, ng-model="user.email", name="email")
      p(class="help-block" ng-show="userFieldForm.email.$invalid">Valid Email Address required

Answered By – reptilicus

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.