使用 ng-repeat 限制行数

limit number of rows with ng-repeat

我想在 table 和 ng-repeat 中最多显示 4 行。如果超过 4 行,我希望第 5 行出现一个加号,单击它时,将显示数据集中的其余行。我不太确定从哪里开始。

table.table.table-striped.table-bordered
  thead
    tr
      th.spacer.col-md-8
        | Products: {{co.products.length}} Total - Click to preview
      th.col-md-2
        span.qty-ordered Qty Ordered
      th.col-md-2
        span.co-price Price
  tbody
    tr ng-repeat="prod in co.products"
        td.co-product-name.col-md-6
          a () {{prod.name}}
        td.col-md-3
          span () XX
        td.col-md-3
          span () {{prod.prices[0].price | currency}}

我会使用 ng-if 来执行此操作,如下所示:

table.table.table-striped.table-bordered
  thead
    tr
      th.spacer.col-md-8
        | Products: {{co.products.length}} Total - Click to preview
      th.col-md-2
        span.qty-ordered Qty Ordered
      th.col-md-2
        span.co-price Price

  tbody ng-if="expanded"
    tr ng-repeat="prod in co.products"
        td.co-product-name.col-md-6
          a () {{prod.name}}
        td.col-md-3
          span () XX
        td.col-md-3
          span () {{prod.prices[0].price | currency}}

  tbody ng-if="!expanded"
    tr ng-repeat="prod in co.products.slice(0,4)"
        td.co-product-name.col-md-6
          a () {{prod.name}}
        td.col-md-3
          span () XX
        td.col-md-3
          span () {{prod.prices[0].price | currency}}
    tr ng-click="expanded = true" show me more...

可以使用$index属性提供的

逻辑将在控制器和模板中。

在控制器中:

$scope.notPlus = true;

在模板中:

tr ng-repeat="prod in co.products" ng-if={{ notPlus and $index < 4}}

并在 link 下方进一步将 noPlus 值翻转为 false

a ng-click={{notPlus = !notPlus}}

这将实现 DRY 原则并使您的代码更易于管理

table.table.table-striped.table-bordered
  thead
    tr
      th.spacer.col-md-8
        | Products: {{co.products.length}} Total - a ng-click={{notPlus = !notPlus}} Click to preview
      th.col-md-2
        span.qty-ordered Qty Ordered
      th.col-md-2
        span.co-price Price
  tbody
    tr ng-repeat="prod in co.products" ng-if={{ notPlus and $index < 4}}
        td.co-product-name.col-md-6
          a () {{prod.name}}
        td.col-md-3
          span () XX
        td.col-md-3
          span () {{prod.prices[0].price | currency}}

使用限制过滤器:

tr ng-repeat="prod in co.products | limitTo : limit"
    td.co-product-name.col-md-6
      a () {{prod.name}}
    td.col-md-3
      span () XX
    td.col-md-3
      span () {{prod.prices[0].price | currency}}
tr ng-show='limit' ng-click='limit = undefined'



# controller

$scope.limit = 4;