I need to duplicate two connected inputs in a form. One is a select field and the other a textarea.
I thought I had found a solution but there's a pretty big bug. When removing the last set of inputs, the previous set is overwritten by the items that were just deleted. This makes sense when I look at the implentation. When a delete happens, the index is updated, and then last set of inputs gets the index from the input that was just deleted and the values are overwritten.
The problem is that I don't know how to fix this. Any ideas?
I have included a plunker here. http://plnkr.co/edit/385RWamBaVSq0Cv5zbmq?p=preview
My controller:
function DuplicateInputCtrl($scope) {
$scope.foodTypes = [
{
"code" : "AP",
"type" : "Apple"
},
{
"code" : "CH",
"type" : "Chicken"
},
{
"code" : "CH",
"type" : "Cheese"
}
]
$scope.foods = [
{
"Selection": "",
"Text": ""
}
]
$scope.cloneItem = function () {
var itemToClone = { "Selection": "", "Text": "" };
$scope.foods.push(itemToClone);
}
$scope.removeItem = function (item) {
$scope.foods.splice(item, 1);
}
}
HTML:
<body ng-controller="DuplicateInputCtrl" class="container">
<div data-ng-repeat="food in foods">
<div class="form-group title-field">
<label for="">Food</label>
<select class="form-control input-full" data-ng-model="food.Selection"
data-ng-options="foodType.code as foodType.type for foodType in foodTypes">
<option value="">Select</option>
</select>
<input type="hidden">
<button data-ng-click="removeItem(food)" class="btn delete-field-{{$index}}">
Delete
</button>
</div>
<div class="form-group">
<textarea class="form-control" data-ng-model="food.Text"></textarea>
</div>
</div>
<button data-ng-click="cloneItem()" class="btn inline">
Add
</button>
</body>