Search code examples
javascripthtmlangularjsonsubmitsubmit-button

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


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.


Solution

  • 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.