shuffle array in ng-repeat angular
Solution 1:
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:
- copy the function so you can use it inside your controller.
- call it in your
$http
result callback:
$http.get('json/questions.json').success(function (data) {
//all questions
$scope.questions = data;
shuffleArray($scope.questions);
...
}
Solution 2:
Use Lodash
_.shuffle(collection)