Sara Williams
Sara Williams

Reputation: 25

AngularJS Pagination with Custom Filters

I'm fairly new to AngularJS code, so I'm still learning my way around.

I'm using the pagination code from this page: http://www.michaelbromley.co.uk/blog/108/paginate-almost-anything-in-angularjs

Now, what I'm trying to do is paginate a list of images. There are custom AngularJS filters for this image list, including file size and image dimensions, which are controlled by checkboxes. The pagination mostly works, except when I click on one of the "filter by" options. Then, there's pagination, but maybe 2 images on one page and 10 on another.

This is the ngRepeat line:

<tr dir-paginate="image in Images | filter: imageSearch | itemsPerPage: 10 | dimBoxes:filterByDim | sizeBoxes: filterBySize | orderBy: predicate" current-page="currentPage">

Here is an example of one of the custom filters:

App.filter('sizeBoxes', function() {
  return function(items, filterBySize) {
    var filtered = [];

    angular.forEach(items, function(item) {
      var fileSize = item.filesize / 1024;

        if (!filterBySize.under500kb && !filterBySize.from500kbto1mb && !filterBySize.over1mb) {
          filtered.push(item);
    }

    if (fileSize < 500 && filterBySize.under500kb) {
      filtered.push(item);
    } else if (fileSize >= 500 && fileSize <= 1024 && filterBySize.from500kbto1mb) {
      filtered.push(item);
    } else if (fileSize > 1024 && filterBySize.over1mb) {
      filtered.push(item);
    }
  });

  return filtered;
  };
});

I saw a couple posts that seemed similar but didn't really apply to my specific situation, I think. Thanks in advance for any help.

Upvotes: 2

Views: 2897

Answers (1)

Michael Bromley
Michael Bromley

Reputation: 4822

I'm think the problem is that you need to put the itemsPerPage filter last, after all of your custom filters.

From the docs:

Note: This filter should come after any other filters in order to work as expected. A safe rule is to always put it at the end of the expression.

So your call to the directive would look like:

<tr dir-paginate="image in Images | filter: imageSearch | dimBoxes:filterByDim | 
                  sizeBoxes: filterBySize | orderBy: predicate | itemsPerPage: 10" 
    current-page="currentPage">

Upvotes: 4

Related Questions