AngularJS validation referencing form object with variable name

865 views Asked by At

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?

1

There are 1 answers

0
reptilicus On BEST ANSWER

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