I\'m creating a quiz and every time I start the quiz I want to shuffle the questions, so that they won\'t appear in the same order every time.
I have this in my htm
Use Lodash
_.shuffle(collection)
Thx to http://bost.ocks.org/mike/shuffle/ use this shuffling function:
Speciality with it is, that the input array stays bindable because the shuffling wont create a new array but instead does the shuffling on the same reference.
// -> 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;
}
side note: lodash's _.shuffle(array)
does not work either because they are creating a new array which breaks binding (so a shuffled array won't trigger the model to be dirty)
To complete the answer to a working solution, following steps should do it:
$http
result callback:$http.get('json/questions.json').success(function (data) {
//all questions
$scope.questions = data;
shuffleArray($scope.questions);
...
}