Using AngularJS how could I randomize the order of

2019-01-19 12:51发布

How would you order a list of items in AngularJS in random order? I was thinking that the built-in orderBy filter would work but I'm not sure how without adding some additional data to the model. Something like would be great.

item in items | orderBy:random

My next thought was to create a custom filter but I'd prefer to avoid that if there is something better already available.

2条回答
乱世女痞
2楼-- · 2019-01-19 13:27

orderBy can take a function parameter, just like array.sort so you can use your HTML above and define a function random on the scope like:

$scope.random = function(){
    return 0.5 - Math.random();
};

This will return a random value sometimes negative, sometimes positive, sometimes 0, which will randomly sort the array.

查看更多
萌系小妹纸
3楼-- · 2019-01-19 13:41

Doing a quick fiddle sh0ber method seems to work well: http://jsfiddle.net/owenmead/fa4v8/1/

<div ng-controller="MyCtrl">
  <p ng-repeat="i in list|orderBy:random">{{i}}</p>
</div>

function MyCtrl($scope) {
  $scope.list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  $scope.random = function() {
    return 0.5 - Math.random();
  }
}

Angular's orderBy uses JavaScript's sort() on a copy of the list. Looking at another answer, certain browsers are stable in their sort, others are not. Perhaps just test the fiddle in a few browsers and you should be good to go: Array.sort Sorting Stability in Different Browsers

PS. Couldn't comment on sh0ber's answer as I don't have 50 rep

查看更多
登录 后发表回答