Search code examples
javascriptangularjspaginationcoffeescriptngtable

AngularJS: Pagination not working for ng-table


So, I'm writing a webapp that gets a big list of student workbooks and puts them in a big table. I'm using ng-table for this. The list is huge so I'm trying to use pagination on the table because otherwise the page just takes forever to load. But right now the pagination is not working, the controls and page numbers show up at the bottom of the table but all the results are on the first page. What a I missing here? Relevant code (written in coffeescript):

$scope.loadWorkbooks = ->
  $scope.workbooks = []
  $scope.filters = {}
  #...some filtering stuff...
  $http.get "/api/students?active=true"
    .then (response) ->
      total = 0
      _.each response.data, (value) ->
        total += value.Workbooks.length

      $scope.workbooksTable = new NgTableParams
        sorting:
          id: 'desc'
        page: 1
        count: 20
        ,
          total: total
          # counts:[]
          getData: ($defer, params) ->
            filteredData = if params.filter() then $filter('filter')($scope.workbooks, params.filter()) else $scope.workbooks
            orderedData = if params.sorting() then $filter('orderBy')(filteredData, params.orderBy()) else filteredData
            $defer.resolve orderedData

      $scope.loadAllWorkbooks()


$scope.loadAllWorkbooks = () ->
  $http.get "/api/v1/students/workbook"
  .then (response) ->
    workbooks = response.data

    if workbooks.length > 0
      $scope.workbooks = $scope.workbooks.concat workbooks
      Materialize.toast "Loading workbooks", 2000
      $scope.workbooksTable.reload()

The table:

<table show-filter="true" class="striped highlight bordered" ng-table="workbooksTable">
      <tr ng-repeat="workbook in $data" ng-show="workbook.state !== 'dead'">
        <td data-title="'ID'" sortable="'id'" filter="{id: 'text'}">
          {{ workbook.id }}
        </td>
        <td data-title="'Student'" sortable="'Student.name'">
          <p>{{ workbook.Student.firstName }} {{ workbook.Student.lastName }}</p>
        </td>
        <!--... more columns...-->
      </tr>
    </table>

Solution

  • Figured it out, I needed to add a line to my get getData function:

    getData: ($defer, params) ->
      filteredData = if params.filter() then $filter('filter')($scope.workbooks, params.filter()) else $scope.workbooks
      orderedData = if params.sorting() then $filter('orderBy')(filteredData, params.orderBy()) else filteredData
      #line I needed to add below
      slicedData = orderedData.slice (params.page() - 1) * params.count(), params.page() * params.count()
      #and then resolve slicedData instead of orderedData
      $defer.resolve slicedData