How to use submit button to submit all details of the form in angularJS

有些话、适合烂在心里 提交于 2019-12-11 11:51:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!