2015-08-27 3 views
0

У меня есть викторина и вы хотите рандомизировать данные, поступающие из моего файла jSON, чтобы каждый раз, когда кто-то пытается попробовать викторину, возникает другой вопрос.Рандомизировать вопросы о задаче quiz

Я наткнулся на this example, но не смог заставить его работать с массивом, исходящим из моего jSON-файла. Смотрите приведенную ниже JS:

.controller('QuizController', ['$scope', '$http', function($scope, $http, $state){ 
    $scope.score = 0; 
    $scope.activeQuestion = -1; 
    $scope.activeQuestionAnswered = 0; 
    $scope.percentage= 0; 

    $http.get('js/quiz_data.json').then(function(quizData){ 
    $scope.myQuestions = quizData.data; 
    $scope.totalQuestions = $scope.myQuestions.length; 
    }); 

    $scope.randomSort = function(myQuestion) { 
    return Math.random(); 
    }; 

HTML:

ng-repeat="myQuestion in myQuestions|orderBy:randomSort"> 

Было бы хорошо, если бы ответы были в случайном порядке также ... Заранее спасибо!

+0

Вы можете поставить пример JSON? – AnotherDeveloper

+0

Да, это так: { \t \t "вопрос": "Qual о Numero всего де biomas нет Brasil?", \t \t "ответы": [ \t \t \t { "ID": 0, "Текст": "27"}, \t \t \t { "ID": 1, "текст": "5"}, \t \t \t { "ID": 2, "текст": "6"}, \t \t \t { «id»: 3, «текст»: «26»} \t \t], \t \t «Правильно»: 2 \t}, –

+0

Возможно ли вернуть результаты из 'GET' уже произвольно заказанного? Как толкнуть эту логику к заднему концу? – ryanyuyu

ответ

1

Это может быть полезным How to randomize (shuffle) a JavaScript array?

Вы можете использовать ту же концепцию на JSON объект

EDIT

function createobj() { 
     var obj = [ 
      {"Question":"This is the first question","Answer":"This is the first Answer"}, 
      {"Question":"This is the second question","Answer":"This is the second Answer"}, 
      {"Question":"This is the third question","Answer":"This is the third Answer"}, 
      {"Question":"This is the forth question","Answer":"This is the forth Answer"}, 
      {"Question":"This is the fifth question","Answer":"This is the fifth Answer"}, 
     ]; 
    //Assigning the obj to the new one 
     obj = randomize(obj); 
    } 

    function randomize (obj) { 
     var index; 
     var temp; 
     for (var i = obj.length - 1; i > 0; i--) { 
      //get random number 
      index = Math.floor((Math.random() * i)); 
      //swapping 
      temp = obj[index]; 
      obj[index] = obj[i]; 
      obj[i] = temp; 
     } 
     //Prints the results into the console 
     for (i = 0; i < obj.length; i++) { 
      console.log(obj[i].Question + ": " + obj[i].Answer); 
     } 
//My edit to pass the obj back to the function 
     return obj; 

    } 

Here is the function, it takes a simple JSON object i created and randomizes it. It will print the results into the Console. Hope this helps more. 
+0

Привет, спасибо за ваш ответ. Я не знаю, как решить мою проблему с вашим советом. Даже при приближении к контексту я не мог решить проблему. Проверьте это: http://jsfiddle.net/q6kv7/ –

+0

Редактирование моего ответа, я сделал простой рандомизатор для вас. –

+0

Спасибо, Джейсон! Извините, что я не знаю js, но, отвечая на ваш вопрос, вы передали json непосредственно на функцию, как мне «связать» json с переменной? –