我正在创建一个测验,每当我开始测验时,我都希望将问题打乱,以免每次出现时都不会以相同的顺序出现。
我在我的html代码中有这个:
<div ng-repeat="question in questions | filter:ids | orderBy:randomSort"> <div id="question">{{question.question}}</div><img id="nextImg" ng-src="../app/img/next.png" ng-click="next()" /> <img class="quizImg" ng-hide="{{question.image}}==null" ng-src="{{question.image}}" /> <div class="answer" ng-repeat="answer in question.answers"> <input type="radio" ng-click="checked(answer)">{{answer.answer}} </div> <!--input id="nextQuestion" type="button" ng-click="next()" value="{{buttonText}}"--> </div>
这在我的控制器中
lycheeControllers.controller('quizCtrl', ['$scope', '$http', function ($scope, $http) { $http.get('json/questions.json').success(function (data) { //all questions $scope.questions = data; $scope.titel = "Check your knowledge about lychees" $scope.randomSort = function(question) { return Math.random(); }; //filter for getting answers / question $scope.ids = function (question) { return question.id == number; } $scope.find = function (id) { if (id == number) { return true; } } $scope.next = function () { if (!(number == (data.length))) { //questionId++; number++; if (correct == true) { points++; } //alert(points); } else { if (!end) { if (correct == true) { points++; end = true; } } alert("Quiz finished: your total score is: " + points); } correct = false; } $scope.checked = function (answer) { //alert(answer.answer); if (answer.correct == "yes") { correct = true; } else { correct = false; } //alert(correct); } }); }]) ;
不幸的是,这根本没有用。希望有人可以帮助我吗?
谢谢 http://bost.ocks.org/mike/shuffle/ 使用此改组功能:
它的特殊之处在于,输入数组保持可绑定性,因为改组不会创建新的数组,而是 对同一引用 执行改组。
// -> Fisher–Yates shuffle algorithm var shuffleArray = function(array) { var m = array.length, t, i; // While there remain elements to shuffle while (m) { // Pick a remaining element… i = Math.floor(Math.random() * m--); // And swap it with the current element. t = array[m]; array[m] = array[i]; array[i] = t; } return array; }
旁注: lodash的方法_.shuffle(array)也不起作用,因为它们正在创建破坏绑定的新数组(因此,经过改组的数组不会触发模型变脏)
_.shuffle(array)
要完成有效解决方案的答案,应执行以下步骤:
$http
$http.get('json/questions.json').success(function (data) { //all questions $scope.questions = data; shuffleArray($scope.questions); ... }