Reputation: 29276
I created a form with an input
text box with dynamically generated ng-model
as below:
<div class="row">
<div class="column">Tags:</div>
<div class="column">
<select data-ng-options="tag.id as tag.name for tag in Tags"
data-ng-model="formData.Tag">
</select>
</div>
</div>
<div data-ng-repeat="choice in choices">
<div class="row">
<div class="column">Result {{$index + 1}}:</div>
<div class="column">
<input type="text" data-ng-model="formData.Result[$index + 1]"
placeholder="Result {{$index + 1}}"><span>
<button data-ng-show="$last" data-ng-click="addAnother()">Add
another</button>
</span>
</div>
</div>
</div>
On submitting the form
, I am getting the data of field Result
as a JSON
below:
{"Tag":"1","Result":{"1":"1", "2":"2"}}
which I want to collect as a list/array
like : {"Tag":"1","Result":["1", "2"]}
.
.js
myapp.controller(‘FormController', function($scope, $http) {
$scope.choices = [ {
id : 'choice1'
} ];
$scope.addAnother = function() {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({
'id' : 'choice' + newItemNo
});
};
$scope.formData = {};
$scope.submit = function() {
$http({
method : 'POST',
url : ‘/Application/submit',
dataType : 'json',
headers : {
'Content-Type' : 'application/json'
},
data : $scope.formData,
});
};
});
Any idea how can I do that?
Thanks.
Upvotes: 1
Views: 541
Reputation: 35853
So, in your controller initialize formData
:
$scope.formData = {
Tag:"",
Result: []
};
and in view use data-ng-model="formData.Result[$index]"
instead of data-ng-model="formData.Result[$index+1]"
.
Here is the plnkr
Upvotes: 3