问题
I am developing a quiz application in angularJS. The HTML code is
`
<div class='question' ng-repeat='question in quiz ' value='{{$index}}'>
<h3>{{$index+1}}. {{question.q}}</h3>
<div ng-repeat = "options in question.options">
<input type='radio'> <strong>{{options.value}}</strong>
</div>
</div>
<input type="button" value="Submit" ng-click= submitAnswer()>
<script src="quizController.js"></script>
</body>
`
And the javascript file is
$scope.submitAnswer =function (){
}
I want when the user answers all the questions, all the values of radio button(answers) should be passed to submitAnswer() on clicking submit button.
回答1:
function quizCtrl($scope) {
$scope.model = {
question: []
};
$scope.quiz = [{
q: 'Question1',
options: [{
value: 'a'
}, {
value: 'b'
}]
}, {
q: 'Question2',
options: [{
value: 'c'
}, {
value: 'd'
}]
}];
$scope.submitAnswer = function() {
console.log($scope.model);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app>
<div ng-controller="quizCtrl">
<div class="question" ng-repeat="question in quiz">
<h3>{{$index+1}}. {{question.q}}</h3>
<div ng-repeat="option in question.options">
<input type="radio" ng-model="model.question[$parent.$index]" value="{{option.value}}">
<strong>{{option.value}}</strong>
</div>
</div>
<input type="button" value="Submit" ng-click="submitAnswer()">
<div>{{model}}</div> <!-- for debugging -->
</div>
</body>
Now every answer to each question will be stored in an array in the model. The structure of the model looks like this:
$scope.model.question[$index] = 'value'
Questions are indexed from 0, so first question is at $scope.model.question[0]
. Now if you want to send it to the API, just send the question
array via $http
.
回答2:
First you need to put your input fields and button inside a form tag. Then add the ng-submit directive to the form and assign to it the submitAnswer() function.
Make sure the type of your button is "submit" as well, not "button".
<form ng-submit="submitAnswer()">
<div class='question' ng-repeat='question in quiz ' value='{{$index}}'>
<h3>{{$index+1}}. {{question.q}}</h3>
<div ng-repeat = "options in question.options">
<input type='radio'> <strong>{{options.value}}</strong>
</div>
</div>
<button type="button">Submit</button>
</form>
来源:https://stackoverflow.com/questions/33326752/how-to-use-submit-button-to-submit-all-details-of-the-form-in-angularjs