在ng-repeat中随机排序

时间:2017-05-01 10:21:25

标签: javascript angularjs angularjs-ng-repeat

我有一个ng-repeat谁循环用户。

JSON:

$scope.peoples = {
    "users": [{
        "name": "Quentin",
        "id": 0,
        "email": "toto@gmail.com",
        "points": "0",
        "sneakers": [{
            "name": "Jordan 1",
            "img": "https://www.flightclub.com/media/catalog/product/cache/1/image/800x570/9df78eab33525d08d6e5fb8d27136e95/8/0/800564_1.jpg"
        }, {
            "name": "Dunk",
            "img": "https://sneakerbardetroit.com/wp-content/uploads/2015/06/nike-sb-dunk-low-primitive-p-rod-2.jpg"
        }, {
            "name": "SB",
            "img": "http://www.nozbone.com/media/catalog/product/cache/1/small_image/295x/040ec09b1e35df139433887a97daa66f/n/i/nike-sb-blazer-vapor-black-white.jpg"
        }, {
            "name": "Air Max",
            "img": "http://www.chausport.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/1/1/11637-chaussures-nike-air-max-95-ultra-essential-grise-vue-exterieure.png"
        }]
    }, ... ]

HTML:

   <div class="battle">
        <div class="battle_block" ng-repeat="user in users | limitTo: 2 | orderBy: random">
            <h3>{{user.name}}</h3>
            <span>{{user.points}}</span>
            <button ng-click="vote(user)">Vote</button>
        </div>
    </div> 

我的控制器内部的随机过滤器(建立在另一个Stackoverflow帖子中):

$scope.random = function() {

    return 0.5 - Math.random();

};

我的问题是ng-repeat总是由json中第一个相同的用户开始(Quentin&amp;第二个)。我想每次都是随机用户,但就目前而言,我没有成功。

2 个答案:

答案 0 :(得分:4)

试试这个:

ng-repeat="user in randomList(users) ..."`

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

您还可以创建随机过滤器,并在ng-repeat中使用此过滤器。

答案 1 :(得分:3)

而不是使用order by,循环函数并返回随机元素

<div class="battle">
        <div class="battle_block" ng-repeat="user in ::random(users) | limitTo: 2>
            <h3>{{user.name}}</h3>
            <span>{{user.points}}</span>
            <button ng-click="vote(user)">Vote</button>
        </div>
</div> 

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