问题
I have a form in angular using tables with input field. Users can add and delete rows. Each cell can be of input type text,number date etc. If the table is too big the form becomes slow. One way to solve this is to paginate the table.
Unfortunately paginating the table is a problem because I have custom validations on the input fields and the form should not submit if any of the fields in any page are not valid. For e.g. The user may fill the first page and submits the form without filling the second page. Angular must throw an error for the fields in the second page. Currently I am using angular implementation of form directive to manage errors. Angular forms only show the fields in the current page and not in the second page.
Take a look at this plunkr . The form is of the below format.
<form name="tableForm" novalidate>
{{tableForm.$valid}}
<button ng-click="previousPage()">Previous</button>
<button ng-click="nextPage()">Next</button>
<table>
<thead>
<tr>
<td>Text</td>
<td>Date</td>
<td>Textarea</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in TableData | limitTo :5:offset">
<td>
<input name="Text_{{$index+offset}}" type="text" ng-model="item.Text" ng-required="true" />
<div ng-messages="tableForm.Text_{{$index+offset}}.$error" ng-messages-include="error-messages" class="errorMsg">
<div ng-message="required" class="error_text">This field is required</div>
</div>
</td>
<td>
<input name="Date{{$index+offset}}" type="date" ng-model="item.Date" />
</td>
<td>
<textarea name="Textarea_{{$index+offset}}" ng-model="item.Textarea" ></textarea>
</td>
</tr>
</tbody>
</table>
</form>
In the table, the text field has a required validation. In the first page, the form is valid as all the text fields are filled. But in the second page, one text field is not filled. So the form should actually be invalid. But it becomes invalid only if I go to the next page.
How do I solve this problem ?
回答1:
As @Stepan Kasyanenko said, if you remove the element from DOM (limitTo does this) validation will not work. If you put the elements in DOM but hide them, then the error messages that are shown will not be very useful as the inputs are not shown to user.
So, you can set a form for each page. The submit button will go to next page if validation for the current page is OK. The submit button on last page will save the form to server. If you would like to save all submitted information, then you can save only the current page on submits to server.
来源:https://stackoverflow.com/questions/39328605/validating-paginated-forms-in-angular-js-1-x