Angular JS-QuizApp — как показать все вопросы

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

Ниже приведен код :

1) индекс.формат html

<!DOCTYPE html>
<html ng-app="quizApp">
<head>
  <meta charset="utf-8" />
  <title>QuizApp</title>
  <link rel="stylesheet" href="style.css" />
  <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  <script src="app.js"></script>
</head>

<body>
  <div class="container">
    <h1 class="title">QuizApp</h1>
    <quiz/>
  </div>
</body>

</html>

2) шаблон.формат html

<div class="quiz-area" ng-show="inProgress">
    <div ng-show="!quizOver">



        <h2 id="question">{{question}}</h2>
        <ul id="options">
            <li ng-repeat="option in options">
                <label>
                    <input type="radio" name="answer" value="{{option}}">
                    {{option}}
                </label>
            </li>
        </ul>


        <div>
            <button ng-click="checkAnswer()" class="next-question">Next</button>


        </div>
    </div>

    <div ng-show="quizOver">
        <h2>Quiz is over</h2>
        <button ng-click="reset()">Play again</button>
    </div>

    <div id="score">
        Score: {{score}}
    </div>
</div>

<div class="intro" ng-show="!inProgress">
    <p>Welcome to the QuizApp</p>
    <button id="startQuiz" ng-click="start()">Start the Quiz</button>
</div>

3) app.js

var app = angular.module('quizApp', []);

app.directive('quiz', function(quizFactory) {
    return {
        restrict: 'AE',
        scope: {},
        templateUrl: 'template.html',
        link: function(scope, elem, attrs) {
            scope.start = function() {
                scope.id = 0;
                scope.quizOver = false;
                scope.inProgress = true;
                scope.getQuestion();
            };

            scope.reset = function() {
                scope.inProgress = false;
                scope.score = 0;
            }

            scope.getQuestion = function() {
                var q = quizFactory.getQuestion(scope.id);
                if(q) {
                    scope.question = q.question;
                    scope.options = q.options;
                    scope.answer = q.answer;
                    scope.trueQId = q.trueQId;
                    scope.falseQid = q.falseQid;
                    scope.answerMode = true;
                } else {
                    scope.quizOver = true;
                }
            };

            scope.checkAnswer = function() {

                if(!$('input[name=answer]:checked').length) return;

                var ans = $('input[name=answer]:checked').val();
                if(ans == scope.options[scope.answer]) {
                    scope.id = scope.trueQId;

                } else {
                    scope.id = scope.falseQid;
                }

                scope.getQuestion();
                scope.answerMode = false;
            };
            scope.reset();
        }
    }
});

app.factory('quizFactory', function() {
    var questions = [
        {
            question: "Which is the largest country in the world by population?",
            options: ["India", "USA", "China", "Russia"],
            answer: 2,
            trueQId:1,
            falseQid:3
        },
        {
            question: "When did the second world war end?",
            options: ["1945", "1939", "1944", "1942"],
            answer: 0,
            trueQId:2,
            falseQid:3
        },
        {
            question: "Which was the first country to issue paper currency?",
            options: ["USA", "France", "Italy", "China"],
            answer: 3,
            trueQId:3,
            falseQid:4
        },
        {
            question: "Which city hosted the 1996 Summer Olympics?",
            options: ["Atlanta", "Sydney", "Athens", "Beijing"],
            answer: 0,
            trueQId:4,
            falseQid:4
        },
        {   
            question: "Who invented telephone?",
            options: ["Albert Einstein", "Alexander Graham Bell", "Isaac Newton", "Marie Curie"],
            answer: 1
        }
    ];

    return {
        getQuestion: function(id) {
            if(id < questions.length) {
                return questions[id];
            } else {
                return false;
            }
        }
    };
});

4) стиль.стиль CSS

body {
    margin: 0 auto;
    text-align: center;
    font-family: 'Helvetica', 'Arial';
}

h2 {
    font-weight: normal;
    font-size: 18px;
}

ul {
    margin: 0;
    padding: 0;
}

li {
    list-style: none;
}

button {
    font-size: 18px;
    cursor: pointer;
}


.container {
    width: 480px;
    margin: 0 auto;
    text-align: left;
}

#options {
    margin: 10px 0;
}

.next-question {
    margin-right: 10px;
}

#score {
    margin-top: 10px;
    font-size: 18px;
    font-weight: bold;
}

1 ответ

  1. внесены некоторые изменения, ваш шаблон.формат html

     <div class="quiz-area" ng-show="inProgress">
     <div ng-show="!quizOver" ng-repeat="option1 in question" ng-init="parentIndex = $index">
      <h2 id="question">{{option1.question}}</h2>
      <div id="options">
         <div ng-model="selected" ng-repeat="option in option1.options">
            <label>
            <input type="radio" ng-value="option.name" ng-model="option.selectedRadio" name="myName{{$parent.$index}}">
            {{option.name}}
            </label>
         </div>
      </div>
      <div>
         <button ng-click="checkAnswer(option1)" class="next-question">Next</button>
      </div>
    </div>
     <div ng-show="quizOver">
      <h2>Quiz is over</h2>
        <button ng-click="reset()">Play again</button>
     </div>
        <div id="score">
         Score: {{score}}
        </div>
     </div>
     <div class="intro" ng-show="!inProgress">
      <p>Welcome to the QuizApp</p>
       <button id="startQuiz" ng-click="start()">Start the Quiz</button>
      </div>
    

    ваше приложение.js

      var app = angular.module('quizApp', []);
    
      app.directive('quiz', function(quizFactory) {
        return {
        restrict: 'AE',
        scope: {},
        templateUrl: 'template.html',
        link: function(scope, elem, attrs) {
            scope.start = function() {
                scope.id = 0;
                scope.score = 0;
                scope.question = [];
                scope.quizOver = false;
                scope.inProgress = true;
                scope.getQuestion();
            };
            scope.reset = function() {
                scope.inProgress = false;
                scope.score = 0;
            }
            scope.getQuestion = function() {
                var q = quizFactory.getQuestion(scope.id);
                console.log(q);
                if (q) {
                    scope.object = {
                        'question': q.question,
                        'options': q.options,
                        'answer': q.answer,
                        'trueQId': q.trueQId,
                        'falseQid': q.falseQid,
                        'answerMode': true,
                        'answers': q.answers
                    }
    
                    scope.question.push(scope.object);
                    console.log(scope.question);
                } else {
                    scope.quizOver = true;
                }
            };
    
            scope.checkAnswer = function(question) {
                var options = question.options;
                for (var i = 0; i < options.length; i++) {
                    if (options[i].selectedRadio) {
                        var ans = options[i].selectedRadio;
                    }
                }
                console.log(question.options[question.answer]);
                if (question.options[question.answer].name == ans) {
                    console.log(ans);
                    scope.score++;
                    scope.question[scope.id].answerMode = false;
                    scope.answerMode = false;
                    scope.id++;
                    scope.getQuestion();
                }
              };
            }
           }
          });
    
      app.factory('quizFactory', function() {
      var questions = [{
        question: "Which is the largest country in the world by population?",
        options: [{
            name: "India",
            selected: false
        }, {
            name: "USA",
            selected: false
        }, {
            name: "China",
            selected: false
        }, {
            name: "Russia",
            selected: false
        }],
        answer: 2,
        trueQId: 1,
        falseQid: 3,
        answers: ""
    }, {
        question: "When did the second world war end?",
        options: [{
            name: "1945",
            selected: false
        }, {
            name: "1934",
            selected: false
        }, {
            name: "1993",
            selected: false
        }, {
            name: "2002",
            selected: false
        }],
        answer: 0,
        trueQId: 2,
        falseQid: 3
    }, {
        question: "Which was the first country to issue paper currency?",
        options: [{
            name: "USA",
            selected: false
        }, {
            name: "France",
            selected: false
        }, {
            name: "Italy",
            selected: false
        }, {
            name: "China",
            selected: false
        }],
        answer: 3,
        trueQId: 3,
        falseQid: 4
    }];
    
    return {
        getQuestion: function(id) {
            console.log(questions);
            if (id < questions.length) {
                return questions[id];
            } else {
                return false;
            }
           },
          updateQuestion: function(id, ans) {
            questions[id].answers = ans;
         }
         };
       });
    

    Надеюсь, это поможет вам(y)