I'm building an order form with multiple select elements added dynamically. The validation is handled by Angular, however validation breaks on cloned elements. Here's a Plunkr
Asked
Active
Viewed 883 times
2 Answers
0
As what Brocco mentioned, cloning the elements won't be the angular way of doing this. You can do it by following these steps:
- Create an array to hold all the newly added
<select>
items. e.g.$scope.dataArray = []
Wrap each form items with an
ng-form
together with anng-repeat
, be sure to use this notation:<div ng-repeat="data in dataArray track by $index" ng-form="dataForm"></div>
to avoid
ng-repeat
duplicates.Create a scope function to add a new dataArray item, similar to your cloning function. e.g:
$scope.addItem = function() { $scope.dataArray.push({}) }
Use dataArray[$index].name as the model to get a direct reference of each item in the
dataArray
array
HTML
<div ng-repeat="data in dataArray track by $index" ng-form="dataForm">
<div class="item">
<div class="form-group" ng-class="{ 'has-error' : dataForm.name.$invalid && submitted }">
<label>Name</label>
<select id="name" name="name" ng-model="dataArray[$index].name"
ng-options="item as item.name for item in items" required></select>
<p ng-show="dataForm.name.$invalid && dataForm.name.$pristine && submitted" class="help-block">You name is required.</p>
</div>
<span class="btn btn-success" ng-click="addItem()"> Add </span>
</div>
</div>
JAVASCRIPT
$scope.dataArray = [{}];
$scope.items = [
{ name: 'Protein 1' },
{ name: 'Protein 2' },
{ name: 'Protein 3' },
{ name: 'Protein 4' },
{ name: 'Protein 5' }
];
$scope.addItem = function() {
$scope.dataArray.push({})
}
See this plunker update.

ryeballar
- 29,658
- 10
- 65
- 74