Shuffle array in ng-repeat angular

I create a quiz, and every time I start a quiz, I want to shuffle the questions so that they do not appear in the same order every time.

I have this in my html code:

<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> 

and this is in my controller

  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); } }); }]) ; 

Unfortunately, this does not work at all. Hope someone can help me with this?

+3
source share
2 answers

thanks to http://bost.ocks.org/mike/shuffle/ use this shuffle function:

The peculiarity is that the input array remains connected, because shuffling will not create a new array, but instead shuffling it using the same link .

 // -> 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; } 

note: lodash _.shuffle(array) does not work either because they create a new array that breaks the binding (so the shuffled array does not start the model to be dirty)


To answer a working solution, follow these steps:

  • copy the function so that it can be used inside your controller.
  • call it in your $http callback:
 $http.get('json/questions.json').success(function (data) { //all questions $scope.questions = data; shuffleArray($scope.questions); ... } 
+19
source

Use lodash

 _.shuffle(collection) 
+1
source

Source: https://habr.com/ru/post/1269505/


All Articles