Coder1 Coder1 - 4 months ago 21
AngularJS Question

Filter results 6 through 10 of 100 with ng-repeat in AngularJS

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.

Is there a built in filter for that?

Answer

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

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

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>

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

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);
      }
    }
  };
}
Comments