2016-07-20 2 views
1

Я пытаюсь сделать простую викторину. До сих пор я создал код, который случайно называет массив возможных вопросов. Теперь я хочу, чтобы пользователь отправил проверочный ящик и выяснил, является ли представленная опция правильной или нет.Как проверить, содержит ли представленный переключатель права правильный ответ

Я думаю, чтобы проверить это, мне нужно сравнить представленную опцию с ответом «Исправить» внутри набора данных. В наборе данных (словарь) у меня есть «Категория», «Неправильно», «Исправить» и т. Д. Поэтому, только если параметр отправки равен «Правильному» предложению, пользователь получит сообщение «правильный ответ».

(function(angular) { 
 

 
    'use strict'; 
 

 
    angular.module('demo', []) 
 
    .controller('repeatController', function($scope) { 
 
     $scope.questions = { 
 
     "0": { 
 
      "Category": "Commas", 
 
      "Correct": "Shirley Chisholm was the first major-party candidate to run for President in a major party. She ran as a Democrat.ANSWER", 
 
      "Given_sen": "\"Shirley Chisholm was the first major party candidate to run for President in a major party, she ran as a Democrat.\"", 
 
      "Incorrect": [ 
 
      "\"Shirley Chisholm, the first major-party candidate to run for President in a major party, she ran as a Democrat.\"", 
 
      "Shirley Chisholm was the first major-party candidate to run for President in a major party: she ran as a Democrat.", 
 
      "Shirley Chisholm was the first major-party candidate to run for President in a major party (she ran as a Democrat)." 
 
      ], 
 
      "Question": "Fix the comma splice.", 
 
      "Rule": "comma splice\n" 
 
     }, 
 

 

 
     "1": { 
 
      "Category": "Commas", 
 
      "Correct": "Hattie McDaniel was the first African-American to win an Oscar. She won for her performance in Gone with the Wind.", 
 
      "Given_sen": "\"Hattie McDaniel was the first African-American to win an Oscar, she won for her performance in Gone with the Wind.\"", 
 
      "Incorrect": [ 
 
      "Hattie McDaniel was the first African-American to win an Oscar: she won for her performance in Gone with the Wind.", 
 
      "\"Hattie McDaniel, the first African-American to win an Oscar, she won for her performance in Gone with the Wind.\"", 
 
      "\"Hattie McDaniel was the first African-American to win an Oscar, for her performance in Gone with the Wind.\"" 
 
      ], 
 
      "Question": "Fix the comma splice.", 
 
      "Rule": "comma splice\n" 
 
     } 
 
     }; 
 

 
     function sort(array) { 
 
     return array.sort(function() { 
 
      return .5 - Math.random(); 
 
     }); 
 
     } 
 

 
     <!-- add correct answer to incorrect answer array and srot it randomly.--> 
 
     function random() { 
 
     for (var key in $scope.questions) { 
 
      $scope.questions[key].Incorrect.push($scope.questions[key].Correct); 
 
      $scope.questions[key].Incorrect = sort($scope.questions[key].Incorrect); 
 
     } 
 
     } 
 

 
     random(); 
 
    }); 
 
})(angular); 
 

 
function myFunction() { 
 
    var x = document.createElement("BUTTON"); 
 
    var t = document.createTextNode("Click me"); 
 
    x.appendChild(t); 
 
    document.body.appendChild(x); 
 
}
<!DOCTYPE html> 
 
<html ng-app="demo"> 
 

 
<head> 
 
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script> 
 
</head> 
 

 
<body ng-controller="repeatController"> 
 

 
    <nav class="navbar navbar-inverse navbar-static-top"> 
 
    <div class="container-fluid"> 
 

 

 
     <div class="navbar-header"> 
 
     <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> 
 
\t \t \t <span class="icon-bar"></span>      
 
\t \t </button> 
 
     </div> 
 
     <div> 
 
     <div class="collapse navbar-collapse" id="myNavbar"> 
 

 
      <ul class="nav navbar-nav navbar-right"> 
 
      <li><a href="About_us.html"><span class="glyphicon glyphicon-check"></span> ABOUT US</a></li> 
 
      <li><a href="Contact_Info.html"><span class="glyphicon glyphicon-envelope"></span>CONTACT INFO</a></li> 
 
      </ul> 
 

 
     </div> 
 
     </div> 
 
    </div> 
 
    </nav> 
 

 
    <form ng-repeat="question in questions"> 
 
    <div class="col-md-12"> 
 
     <div class="well"><b> QUESTION: {{question.Question}}</b> 
 
     <br> Category: {{question.Category}} </div> 
 
     <div class="radio" ng-repeat="incorrect_answer in question.Incorrect"> 
 
     <label> 
 
      <input type="radio" name="radio{{$parent.$index}}" value="{{incorrect_answer}}"> {{incorrect_answer}} 
 
     </label> 
 
     </div> 
 
     <!-- 
 
     <div class="form-group"> 
 
     <label class="radio-inline"> 
 
      <input type="radio"> {{question.Correct}} 
 
     </label> 
 
     </div> 
 
--> 
 
     <div class="form-group" onsubmit="TestFunction()"> 
 
     <input class="btn btn-primary" type="submit" value="Submit"> 
 
     </div> 
 
    </div> 
 
    </form> 
 
</body>

ответ

0

Прежде всего, необходимо использовать ng-model в вашем radio button, то вы можете просто проверить с помощью ng-submit если выбранная кнопка в этом index равно правильный ответ, просто, как показано ниже:

(function(angular) { 
 
    'use strict'; 
 
    angular 
 
    .module('demo', []) 
 
    .controller('repeatController', repeatController); 
 

 
    function repeatController($scope) { 
 
    $scope.radio = []; 
 
    $scope.message = []; 
 

 
    $scope.questions = { 
 
     "0": { 
 
     "Category": "Commas", 
 
     "Correct": "Shirley Chisholm was the first major-party candidate to run for President in a major party. She ran as a Democrat.ANSWER", 
 
     "Given_sen": "\"Shirley Chisholm was the first major party candidate to run for President in a major party, she ran as a Democrat.\"", 
 
     "Incorrect": [ 
 
      "\"Shirley Chisholm, the first major-party candidate to run for President in a major party, she ran as a Democrat.\"", 
 
      "Shirley Chisholm was the first major-party candidate to run for President in a major party: she ran as a Democrat.", 
 
      "Shirley Chisholm was the first major-party candidate to run for President in a major party (she ran as a Democrat)." 
 
     ], 
 
     "Question": "Fix the comma splice.", 
 
     "Rule": "comma splice\n" 
 
     }, 
 

 

 
     "1": { 
 
     "Category": "Commas", 
 
     "Correct": "Hattie McDaniel was the first African-American to win an Oscar. She won for her performance in Gone with the Wind.", 
 
     "Given_sen": "\"Hattie McDaniel was the first African-American to win an Oscar, she won for her performance in Gone with the Wind.\"", 
 
     "Incorrect": [ 
 
      "Hattie McDaniel was the first African-American to win an Oscar: she won for her performance in Gone with the Wind.", 
 
      "\"Hattie McDaniel, the first African-American to win an Oscar, she won for her performance in Gone with the Wind.\"", 
 
      "\"Hattie McDaniel was the first African-American to win an Oscar, for her performance in Gone with the Wind.\"" 
 
     ], 
 
     "Question": "Fix the comma splice.", 
 
     "Rule": "comma splice\n" 
 
     } 
 
    }; 
 

 
    function sort(array) { 
 
     return array.sort(function() { 
 
     return .5 - Math.random(); 
 
     }); 
 
    } 
 

 
    function random() { 
 
     for (var key in $scope.questions) { 
 
     $scope.questions[key].Incorrect.push($scope.questions[key].Correct); 
 
     $scope.questions[key].Incorrect = sort($scope.questions[key].Incorrect); 
 
     } 
 
    } 
 

 
    random(); 
 

 
    $scope.submit = function(index) { 
 
     if ($scope.questions[index].Correct == $scope.radio.selected[index]) { 
 
     $scope.message[index] = "Correct"; 
 
     } else { 
 
     $scope.message[index] = "Incorrect"; 
 
     } 
 
    } 
 
    } 
 
})(angular);
<!DOCTYPE html> 
 
<html ng-app="demo"> 
 

 
<head> 
 
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script> 
 
</head> 
 

 
<body ng-controller="repeatController"> 
 
    <nav class="navbar navbar-inverse navbar-static-top"> 
 
    <div class="container-fluid"> 
 
     <div class="navbar-header"> 
 
     <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> 
 
      <span class="icon-bar"></span> 
 
     </button> 
 
     </div> 
 
     <div> 
 
     <div class="collapse navbar-collapse" id="myNavbar"> 
 
      <ul class="nav navbar-nav navbar-right"> 
 
      <li><a href="About_us.html"><span class="glyphicon glyphicon-check"></span> ABOUT US</a></li> 
 
      <li><a href="Contact_Info.html"><span class="glyphicon glyphicon-envelope"></span>CONTACT INFO</a></li> 
 
      </ul> 
 
     </div> 
 
     </div> 
 
    </div> 
 
    </nav> 
 
    <form name="form" novalidate ng-repeat="question in questions" ng-submit="submit($index)"> 
 
    <div class="col-md-12"> 
 
     <div class="well"><b> QUESTION: {{question.Question}}</b> 
 
     <br> Category: {{question.Category}} </div> 
 
     <div class="radio" ng-repeat="incorrect_answer in question.Incorrect"> 
 
     <label> 
 
      <input type="radio" ng-model="radio.selected[$parent.$index]" ng-value="incorrect_answer" name="radio{{$parent.$index}}"> {{incorrect_answer}} 
 
     </label> 
 
     </div> 
 
     <div class="form-group"> 
 
     <input class="btn btn-primary" type="submit" value="Submit"> 
 
     <span ng-class="{ 'text-success': message[$index] == 'Correct', 'text-danger': message[$index] == 'Incorrect' }" ng-if="message[$index]" ng-bind="message[$index]"></span> 
 
     </div> 
 
    </div> 
 
    </form> 
 
</body>

+0

Большое вам спасибо. Кстати. что мне нужно добавить, если я хочу увидеть только одну проблему сразу. скажем, у меня есть 100 наборов задач, и пользователь может просматривать только один из них за раз. Возможно, мне нужно правильно использовать ng-hide и ng-show. или нужно сделать переменную и увеличить ее после подачи одного вопроса. –

+0

Я получил его nevermind –

+0

Рад, что помогло :) Сначала вы должны удалить 'ngRepeat' из своей формы .. так что вы можете показывать 1 на 1, увеличивая переменную в вашей функции' ngSubmit' и передавая currentindex вашему представлению. . вы поняли это? Также я предлагаю вам поместить его в вашу кнопку '' ':' ng-disabled = "! Radio.selected [$ index]" '. – developer033

0

Вы можете проверить значение атрибута с myElement.getAttribute('value'). Итак:

var correctAnswer = 'apples'; 

var myRadio = document.getElementById('myRadio'); 

var isCorrect = myRadio.getAttribute('value') === correctAnswer; 

console.log('is correct? ' + isCorrect); 

Вы можете также захватить все кнопки радио с тем же значением атрибута имя и затем цикл над ними, глядя на их checked собственности, и (если установлен) разорвать петлю и вернуть, что радиостанции value.

+0

Это не угловой способ делать вещи. – developer033

+0

А, справедливая точка. В формулировке в вопросе даже не упоминалось «Угловое», поэтому я не рассматривал это. –

+0

Правда, но он помечен как 'angularJs', и он явно использует .. также это не критика, просто точка. – developer033

Смежные вопросы