Search code examples
angularjsangular-filters

Issues with $filter('limitTo') in angularjs


Having issues with using the limitTo filter through javascript

The angularjs docs for limitTo state that the filter is to be used in the following way:

$filter('limitTo')(input, limit, begin)

please note the begin parameter is optional.

Following from the above I did the following:

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

function MyCtrl($scope,$filter) {
   $scope.numbers =[1,2,4,1,8,11,345,123,908,223,4646,132,24,43,3,76,432,1];
   $filter('limitTo')($scope.numbers, 3);   
}

<div ng-controller="MyCtrl">
 {{numbers}}
</div>

I expect my output to be

[1,2,4]

Yet the whole array was shown meaning the limitTo filter didn't work.

What am I doing wrong?

Link to jsfiddle


Solution

  • Angular's $filter doesn't modify the original array, so you have to do it like this:

    $scope.filteredArray = $filter('limitTo')($scope.numbers, 3);