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>
0

2 Answers 2

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

1 Comment

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.
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>

1 Comment

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' jsfiddle.net/6H8Xx/270.

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.