shuffle array in ng-repeat angular

隐身守侯 提交于 2019-11-27 15:20:40

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

  ...
}

Use Lodash

_.shuffle(collection)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!