michaelbromley / angularUtils

A place where I will collect useful re-usable Angular components that I make
MIT License
2k stars 858 forks source link

dirPagination: accessing visible repeated items #437

Open npapazian opened 7 years ago

npapazian commented 7 years ago

Hey Michael --

First thanks for all the work you've put into this.

I'm using dirPagination on a table with repeated rows and i'm trying to implement a method that will select the rows that are on the current page rather than ALL of the rows. Is there an out of the box way to select ONLY the current page's rows when using the 'select all' checkbox' ?

Here's a plunkr with the select all method hitting all rows across pages. http://plnkr.co/edit/ZwzCzhc1vUgOS4gHZjzd?p=preview

Is there a subset of the $scope.collection that I can access?

This StackOverflow question gets at the behavior I'm looking for, but the solution seems very hacky.

michaelbromley commented 7 years ago

Hi,

Wow, that StackOverflow solution is truly disgusting! 😆

There is a much more simple way to do this: check my modified version of your Plunker: http://plnkr.co/edit/r5EB1CYeiruHqwaiWFTx?p=preview

Here is the relevant code:


  $scope.toggleAll = function() {
    var toggleStatus = !allOnCurrentPageSelected();
    thisPageItems()
      .forEach(function(item) {
        item.selected = toggleStatus;
      });
  }

  // Attach to $scope so we can use it in the template to 
  // set the state of the "check all" checkbox
  $scope.allSelected = allOnCurrentPageSelected;

  // Returns an array containing all the items on the current page
  function thisPageItems() {
    var start = ($scope.currentPage - 1) * $scope.pageSize;
    var end = start + $scope.pageSize;
    return $scope.collection
      .filter(function(item, index) {
        return start <= index && index < end;
      });
  }

  // Returns true if all items on the current page are selected
  function allOnCurrentPageSelected() {
    return thisPageItems().every(function(item) {
      return item.selected;
    });
  }

Hope that helps,

Michael