greengrassbluesky
greengrassbluesky

Reputation: 373

Examine $dirty and $invalid for Dynamic Field Names in Angular JS version 1.1.5

I have dynamic field names such as below: Here field names are coming from the controller and are generated dynamically. I am trying to do validations and I want to print $dirty and $invalid flag for them.

<div ng-repeat="fruit in fruits">
<ng-form name="myForm">
**dirty: {{myForm.fruitId_[fruit.fruitname].$dirty}}
invalid: {{myForm.fruitId_[fruit.fruitname].$invalid}}**

This field is required Please enter at the most 8 characters

Here the below two statements :

**dirty: {{myForm.fruitId_[fruit.fruitname].$dirty}}
invalid: {{myForm.fruitId_[fruit.fruitname].$invalid}}**  

Don't display anything. I appreciate your inputs.

Here is the plunker : http://plnkr.co/edit/ehe3mNknCXV5PzDrxl8z?p=preview

FIX: I figured that angular needs {{}} for the field name in version1.1.5 and these brackets need to be escaped too.

<ng-form name="myForm"> 
      <div ng-repeat="fruit in fruits">

       dirty: {{myForm['\{\{fruit.fruitname\}\}'].$dirty}}
       invalid: {{myForm['\{\{fruit.fruitname\}\}'].$invalid}} 
       {{fruit.fruitname}} Textbox: <input type="text" name="{{fruit.fruitname}}" auto-id="fruitId_{{color}}_{{fruit.fruitname}}" ng-required="true" ng-maxlength="8" ng-model="data[fruit.fruitname]"  />
                <div class="validation-message" ng-show="myForm['\{\{fruit.fruitname\}\}'].$dirty && myForm['\{\{fruit.fruitname\}\}'].$invalid">
                    <span ng-show="myForm['\{\{fruit.fruitname\}\}'].$error.required">This field is required</span>
                    <span ng-show="myForm['\{\{fruit.fruitname\}\}'].$error.maxlength">Please enter at the most 8 characters</span>
                </div>

       </div>

  </ng-form>

I updated the plunker with working version - http://plnkr.co/edit/SmwXXI38mgED7UJNtjuE?p=preview.

Upvotes: 1

Views: 1098

Answers (1)

JB Nizet
JB Nizet

Reputation: 692073

There are several problems in the posted code:

  1. You're using an obsolete version of angular. Use the last stable one, which does support dynamic fields
  2. You have one form per field, always with the same name, instead of a global form
  3. you repeat the name "myForm" in the name of the fields themselves. This is unnecessary and confusing
  4. the name used in your expression is invalid.

Here's a working example:

<form name="myForm">
  <div ng-repeat="fruit in fruits">
   dirty: {{myForm['fruitId_' + fruit.fruitname].$dirty}}
   invalid: {{myForm['fruitId_' + fruit.fruitname].$invalid}}  
   {{fruit.fruitname}} Textbox: <input type="text" name="fruitId_{{fruit.fruitname}}" ng-required="true" ng-model="data[fruit.fruitname]" />
  </div>
</form>

Upvotes: 1

Related Questions