6

I am want to build a nested form using ng-repeat like following. Since my input fields are required, I want to add a error message in the next line with something like this: <span ng-show="submitted && editableForm.[e.name].$error.required" class="error">Required field</span>, I know this is wrong "editableForm.[e.name].$error.required", what is the right way to do this?

UPDATE Just tried adding <ng-form name="rowForm">, but this only works when I use a hardcode name attribute, in my case this is dynamically generated in [e.name]

Thanks Leo

NESTED FORM

<form name="editableForm" novalidate="novalidate"><div class="newEditable">
  <ul ng-repeat="row in newRows">
    <li ng-repeat="e in rowAttrs">
     <input type="text" ng-model="newRows[e.name]" name="e.name" ng-required="e.required">
    </li>
    <li><a href="" ng-click="rm_row($index)">x</li>
  </ul>
  </div><a href="" ng-click="newRow()">{{add}}</a>
  <a ng-show="newRows.length > 0" ng-click="saveIt(editableForm)">{{save}}</a>
</form>
Manuel Bitto
  • 5,073
  • 6
  • 39
  • 47
user1883793
  • 4,011
  • 11
  • 36
  • 65

2 Answers2

10

For this specific code example you also need to add an ng-form attribute to the first ng-repeat:

<ul ng-repeat="row in newRows" ng-form="innerForm">

You can now do something similar with your original solution to highlight the required field:

<div class="validation_error" ng-show="e.required && innerForm['\{\{e.name\}\}'].$error.required">
    Required
</div>
snumpy
  • 2,808
  • 6
  • 24
  • 39
Alex Pop
  • 655
  • 1
  • 11
  • 20
  • I have used the solution described in my answer to dynamically render form fields within a containing form and ensure their validation state is propagated to the containing form i.e. the user should not be able to click submit if any of the dynamically rendered form fields is required and it does not have a valid value. – Alex Pop Feb 11 '14 at 12:15
4

Solved by adding escape to the dynamic name, jsfiddle.net/langdonx/6H8Xx/2

Code

<div class="validation_error" ng-show="e.required && rowForm['\{\{e.name\}\}'].$error.required">
  Required
</div>
Boycs
  • 5,610
  • 2
  • 28
  • 23
user1883793
  • 4,011
  • 11
  • 36
  • 65
  • 1
    What's actually happening here is the you're creating a rowForm.{{e.name}} property that isn't dynamic. The actual name of the property is {{e.name}} which is why escaping it works. Your jsfiddle also has the correct fix which is creating an inner form called "form". Each inner form has a {{e.name}} property, but they aren't dynamic properties. You can see it working here by changing {{e.name}} to 'field' http://jsfiddle.net/6H8Xx/270/. – Erik Ringsmuth May 15 '14 at 21:27