每隔第4列在ng-repeat中排序

时间:2015-11-24 13:08:11

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

要创建每行最多包含4个商品的商品网格we can do the following

<div ng-repeat="product in products" ng-if="$index % 4 == 0" class="row">
    <div class="col-xs-4">{{products[$index]}}</div>
    <div class="col-xs-4">{{products[$index + 1]}}</div>
    <div class="col-xs-4">{{products[$index + 2]}}</div>
    <div class="col-xs-4">{{products[$index + 3]}}</div>
</div>

但是,如果我尝试添加:

<div ng-repeat="product in products | orderBy: '-value.timestamp_creation'" ng-if="$index % 4 == 0" class="row">
      <!-- see above -->
</div>

其中products如下所示(数组):

[
  {name: "John", value: {timestamp_creation: 1}}, 
  {name: "Andrew", value: {timestamp_creation: 4}},
  {name: "Senior", value: {timestamp_creation: 2}}
  {name: "Dog", value: {timestamp_creation: 3}}
]

然后它不能对网格进行排序。它只显示顺序1,4,2,3。

请注意,以下对网格进行排序的方法有效(但之后我不会在每第4列后得到一行)

<div ng-repeat="product in products | orderBy: '-value.timestamp_creation'" class="row">
    <div class="col-xs-4">{{product}}</div>
</div>

那么如何结合这两种方法,在每第4项之后获得一列,但仍能对列表进行排序?

1 个答案:

答案 0 :(得分:1)

它应该工作。你正在使用哪种角度版本。我检查了每一排第二排。

请参阅Working Fiddle

<强> HTML

<div ng-controller="MyCtrl">
  <div ng-repeat="product in products | orderBy: '-value.timestamp_creation'" ng-if="$index % 2 === 0" class="row">
    <div class="col-xs-4">{{product}}</div>
</div>
</div>

<强>控制器

function MyCtrl($scope) {
    $scope.products = [
        {name: "John", value: {timestamp_creation: 1}}, 
        {name: "Andrew", value: {timestamp_creation: 4}},
        {name: "Senior", value: {timestamp_creation: 2}},
        {name: "Dog", value: {timestamp_creation: 3}},
        {name: "John 1", value: {timestamp_creation: 7}}, 
        {name: "Andrew 1", value: {timestamp_creation: 6}},
        {name: "Senior 1", value: {timestamp_creation: 8}},
        {name: "Dog 1", value: {timestamp_creation: 5}}
    ];
}