Reputation: 1402
When creating a new poll, the question and all the potential answers need to be send to the controller
once submitted. I know how to work with ng-model
, but I have no clue how I can bind it to an array
in that array.
For example, my array looks like this:
var question = {
"question":"",
"choices": [
{
"id":1,
"choice": "Yes"
},
{
"id"=2,
"choice": "No"
}
]
}
<form novalidate name="questionForm" ng-submit="addVote(vote)">
<input placeholder="Type your question..." name="question" ng-model="vote.question" />
<input ng-model="" value="Choice 1" />
<input ng-model="" value="Choice 2" />
<button type='submit' class="circle-btn btn-send ion-ios-paperplane"></button>
</form>
The input[name=question]
will obviously send whatever is in that input
box to vote.question
. But how do I add those potential answers to the choices
array
?
So in short: I need to be able to bind {id:1, choice: value of input}
Upvotes: 0
Views: 1938
Reputation: 18895
You can make your vote
variable an object literal that contains the question and the array of answer choices (could be empty array):
In the controller:
$scope.vote = {
"question": 'question stem title here',
"answerChoices": [
{"id": 1, "choice": 'Yes'},
{"id": 2, "choice": 'No'},
]
};
In the HTML:
<form novalidate name="questionForm" ng-submit="addVote(vote)">
<input placeholder="Type your question..." name="question" ng-model="vote.question" />
<span ng-repeat="choice in vote.answerChoices track by $index">
<input class="form-control" ng-model="vote.answerChoices[$index]" />
</span>
<button type='submit' class="circle-btn btn-send ion-ios-paperplane"></button>
</form>
You can push
the new answer choices to the vote.answerChoices
array programmatically
Upvotes: 2
Reputation: 692121
Just use ng-repeat to iterate on the choices, and display one input per element of the array, bound to the choice field of this element:
<div ng-repeat="element in vote.choices">
<input ng-model="element.choice" />
</div>
Upvotes: 1