Reputation: 90
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
http://plnkr.co/edit/TqofTw6K7nvLJzPEYAi3?p=preview
Upvotes: 0
Views: 889
Reputation: 30118
As what Brocco mentioned, cloning the elements won't be the angular way of doing this. You can do it by following these steps:
<select>
items. e.g. $scope.dataArray = []
Wrap each form items with an ng-form
together with an ng-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.
Upvotes: 0