Vincent_zhang
Vincent_zhang

Reputation: 23

Angularjs filter limit to include two params

I want to use it just as limitTo(input,begin,end)? How to set the begin index?

Upvotes: 1

Views: 11184

Answers (3)

Dalorzo
Dalorzo

Reputation: 20014

On Version 1.4

As highlighted by @doldt Angular 1.4 now added the feature to indicate the begin of and end of in the limit:

{{ limitTo_expression | limitTo : limit : begin}}

https://code.angularjs.org/1.4.0/docs/api/ng/filter/limitTo

Previous version 1.4 Angular limitTo does not support more than one argument:

{{ limitTo_expression | limitTo : limit}}

The filter limitTo creates a new array or string containing only the specified number of elements in the limit argument.

Therefore the recommended option is to create a custom filter.

For example here is an Online Demo and this is how you can do it:

Please note that the first argument of the filter is the "Data Source" ( the entire list). It is the purpose of the filter to filter the Data Source.

HTML Sample

<ul ng-controller="myCtrl">
    <li ng-repeat="row in friends |myFilter:2:5 ">{{row.name}}</li>
<ul>

Js App and filter creation

var myApp = angular.module('myApp',[]);

myApp.filter('myFilter', function() {
        return function(items, begin, end) {                                     

            return items.slice( begin, end);
        }
    });

function myCtrl($scope)
{    
    $scope.friends = [
      {name:'John', age:25, gender:'boy'},
      {name:'Jessie', age:30, gender:'girl'},
      {name:'Johanna', age:28, gender:'girl'},
      {name:'Joy', age:15, gender:'girl'},
      {name:'Mary', age:28, gender:'girl'},
      {name:'Peter', age:95, gender:'boy'},
      {name:'Sebastian', age:50, gender:'boy'},
      {name:'Erika', age:27, gender:'girl'},
      {name:'Patrick', age:40, gender:'boy'},
      {name:'Samantha', age:60, gender:'girl'}
    ];
}

myApp.controller('myCtrl',myCtrl);

Upvotes: 5

Alexey
Alexey

Reputation: 1330

You may achive the disired result by sequential application of limitTo filter to the array. Say you want to extract items from 4 to 9:

HTML:

{{ someArray | limitTo: to | limitTo: from}}

JS

var from = 4;
$scope.to = 9;
$scope.from = from - $scope.to; // This value must be a negative 

Upvotes: 1

Subash Selvaraj
Subash Selvaraj

Reputation: 3385

Create your own filter to achieve this. Try below,

app.filter('limitFromTo', function(){
    return function(input, from, to){
        return (input != undefined)? input.slice(from, to) : '';
    }
});

Usage:

{{ limitTo_expression | limitFromTo : from : to}}

Upvotes: 1

Related Questions