角度ng重复多重排序

时间:2014-12-19 17:55:02

标签: javascript angularjs angularjs-ng-repeat angularjs-filter

我有一系列对象,我试图以特定的方式排序:

[
  {
    name: 'Blackcurrant',
    created_at: '3/2/2014'
  },{
    name: 'Bilberry',
    created_at: '1/2/2013'
  },{
    name: 'Apple',
    created_at: '11/5/2012'
  },{
    name: 'Boysenberry',
    created_at: '1/1/2014'
  },{
    name: 'Coconut',
    created_at: '3/4/2011'
  },{
    name: 'Breadfruit',
    created_at: '6/6/2013'
  },{
    name: 'Currant',
    created_at: '2/8/2014'
  },{
    name: 'Avocado',
    created_at: '5/13/2014'
  },{
    name: 'Banana',
    created_at: '7/16/2014'
  },{
    name: 'Blueberry',
    created_at: '1/18/2010'
  },{
    name: 'Apricot',
    created_at: '9/17/2014'
  },{
    name: 'Date',
    created_at: '2/22/2012'
  },{
    name: 'Damson',
    created_at: '10/10/2014'
  },{
    name: 'Cantaloupe',
    created_at: '8/13/2014'
  },{
    name: 'Cranberry',
    created_at: '4/25/2011'
  },{
    name: 'Cucumber',
    created_at: '7/6/2014'
  },{
    name: 'Blackberry',
    created_at: '2/10/2014'
  },{
    name: 'Cloudberry',
    created_at: '1/23/2014'
  },{
    name: 'Cherry',
    created_at: '7/11/2013'
  },{
    name: 'Cherimoya',
    created_at: '11/19/2014'
  }
]

我需要能够设置它,以便当我进行ng-repeat时,椰子,香蕉,哈密瓜和樱桃在开始时按顺序显示,然后按照created_at日期对它们进行排序。是否可以使用orderBy和过滤器的组合?

2 个答案:

答案 0 :(得分:1)

您可以使用created_at过滤器设置重复项,按orderBy属性对ngRepeat元素进行排序。

<li ng-repeat="food in arrFoods | orderBy:created_at">
    <span>{{food.name}}</span>
</li>

至于确保你首先出现“椰子,香蕉,哈密瓜和樱桃”,你需要根据一定的价值创建自己的排序方法。对于我的例子,我添加了属性 fave 按照created_by订购之前,您希望在数组顶部显示的元素。

{
    name: 'Coconut',
    created_at: '3/4/2011',
    fave: true
}

然后将其应用于ngRepeat元素...

<li data-ng-repeat="food in arrFoods | orderBy:['fave', 'created_by']">

通过应用排序参数数组,我们优先考虑将fave设置为true的元素(不需要将其他设置为false),然后按created_by排序。

>>Working Plunkr Example

-mbp

答案 1 :(得分:0)

这就是我最终做的事情:

.filter('fruitSort', function() {
  return function(fruits) {
    var favoriteFruit = [];
    var newFruit = [];

    angular.forEach(fruits, function(fruit) {
      if (fruit.name === 'Coconut' || fruit.name === 'Banana' || fruit.name === 'Cantaloupe' || fruit.name === 'Cherry') {
        if (fruit.name === 'Coconut') {
          favoriteFruit[0] = circle;
        } else if (fruit.name === 'Banana') {
          favoriteFruit[1] = circle;
        } else if (fruit.name === 'Cantaloupe') {
          favoriteFruit[2] = circle;
        } else {
          favoriteFruit[3] = circle;
        }
      } else {
        newFruit.push(circle);
      }
    });

    newFruit.sort(function(a,b){return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();});
    var sortedFruit = favoriteFruit.concat(newFruit);

    return sortedFruit;
  };
})