Check out my Plunker demo:
http://plnkr.co/edit/sm3r4waKZkhd6Wvh0JdB?p=preview
I have a dynamic set of form elements that users can add and remove. I am looking to include an 'id' property for each object in the form elements, corresponding to their index position.
For example, the current structure is:
[ { "Selection": "", "Text": "" }, { "Selection": "", "Text": "" } ]
I want it to be structured like this:
[ { "Selection": "", "Text": "", "Id" : "1" }, { "Selection": "", "Text": "", Id : "2" } ]
This is the controller code snippet:
function DuplicateInputCtrl($scope) {
$scope.foodTypes = [
{
"code" : "AP",
"type" : "Apple"
},
{
"code" : "CH",
"type" : "Chicken"
},
{
"code" : "GR",
"type" : "Grape"
}
]
$scope.foods = [
{
"Selection": "",
"Text": ""
}
]
$scope.cloneItem = function () {
var itemToClone = { "Selection": "", "Text": "" };
$scope.foods.push(itemToClone);
}
$scope.removeItem = function (item) {
$scope.foods.splice(item, 1);
}
$scope.saveForm = function () {
console.log($scope.foods);
}
This is the HTML code snippet:
<body ng-controller="DuplicateInputCtrl" class="container">
<div data-ng-repeat="food in foods">
<div class="form-group title-field">
<label for="">Food {{ $index + 1 }}</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($index)" 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>
<div>
<button class="btn btn-medium" ng-click="saveForm()">Save</button>
</div>
{{ foods | json }}
</body>