在 AngularJS 中使用 ng-repeat 过滤结果 6 到 10 of 100 [英] Filter results 6 through 10 of 100 with ng-repeat in AngularJS

查看:14
本文介绍了在 AngularJS 中使用 ng-repeat 过滤结果 6 到 10 of 100的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文档中看到 limitTo 过滤器,它允许我限制前 5 个或最后 5 个结果,但我想设置限制的开始位置,以便我可以显示第二组5 个结果.

I see the limitTo filter in the docs, which allows me to limit the first 5, or last 5 results, but I want to set where my limit starts so I can show the second set of 5 results.

是否有内置过滤器?

推荐答案

自 Angular 1.4.0 起,limitTo 过滤器采用可选的begin 参数:

Since Angular 1.4.0, the limitTo filter takes an optional begin argument:

<div ng-repeat="item in items | limitTo:5:5">{{item}}</div>

在旧版本中,编写自定义过滤器相当简单.这是一个基于 Array#slice 的简单实现(注意你传递的是第一个和最后一个索引,而不是一个计数):

In older versions, writing a custom filter is fairly straightforward. Here's a naïve implementation based on Array#slice (note you pass the first and last index, instead of a count):

app.filter('slice', function() {
  return function(arr, start, end) {
    return (arr || []).slice(start, end);
  };
});

<div ng-repeat="item in items | slice:6:10">{{item}}</div>

工作 jsFiddle:http://jsfiddle.net/BinaryMuse/vQUsS/

Working jsFiddle: http://jsfiddle.net/BinaryMuse/vQUsS/

或者,您可以简单地窃取 整个 Angular 1.4.0 实现limitTo:

Alternatively, you can simply steal the entire Angular 1.4.0 implementation of limitTo:

function limitToFilter() {
  return function(input, limit, begin) {
    if (Math.abs(Number(limit)) === Infinity) {
      limit = Number(limit);
    } else {
      limit = toInt(limit);
    }
    if (isNaN(limit)) return input;

    if (isNumber(input)) input = input.toString();
    if (!isArray(input) && !isString(input)) return input;

    begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
    begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin;

    if (limit >= 0) {
      return input.slice(begin, begin + limit);
    } else {
      if (begin === 0) {
        return input.slice(limit, input.length);
      } else {
        return input.slice(Math.max(0, begin + limit), begin);
      }
    }
  };
}

这篇关于在 AngularJS 中使用 ng-repeat 过滤结果 6 到 10 of 100的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆