shuffle array in ng-repeat angular

后端 未结 2 1511
太阳男子
太阳男子 2020-12-01 22:25

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

相关标签:
2条回答
  • 2020-12-01 23:10

    Use Lodash

    _.shuffle(collection)
    
    0 讨论(0)
  • 2020-12-01 23:13

    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);
    
      ...
    }
    
    0 讨论(0)
提交回复
热议问题