Search code examples
angularjsngtable

angularjs ng-table pagination issue


I've run into a problem with ng-table and pagination. Basically I have two datasets and the user can choose which is rendered in the table.

With dataset one there are 2 pages and with dataset two there is only one page. The issue now is that if I navigate to page 2 and then change to dataset 2, I get a blank table with no paging options.

Plunker created below in which you can test this: http://plnkr.co/edit/0D4ih7bPNf3Jz87Rymc7

My code is pretty much just a copy and paste from an ngtable example:

var app = angular.module('main', ['ngTable']).
controller('DemoCtrl', function($scope, $filter, ngTableParams) {

$scope.datasets = ["1","2"];
$scope.dataset = "1";
var data1 = [{name: "One", age: 50},
            {name: "Two", age: 43},
            {name: "Three", age: 27},
            {name: "Four", age: 29},
            {name: "Five", age: 34},
            {name: "Six", age: 43},
            {name: "Seven", age: 27},
            {name: "Eight", age: 29},
            {name: "Nine", age: 34},
            {name: "Ten", age: 43},
            {name: "Eleven", age: 27},
            {name: "Twelve", age: 29},
            {name: "Thirteen", age: 34},
            {name: "Fourteen", age: 43},
            {name: "Fifteen", age: 27},
            {name: "Sixteen", age: 29}];

var data2 = [{name: "Jacob", age: 50},
            {name: "Jacob", age: 43},
            {name: "Jacob", age: 27}];

var getData = function() {
    return $scope.dataset === "1" ? data1 : data2;
};
$scope.$watch("dataset", function () {
    $scope.tableParams.reload();
});         
$scope.tableParams = new ngTableParams({
    page: 1,            // show first page
    count: 10,          // count per page
    sorting: {
        name: 'asc'     // initial sorting
    }
}, {
    total: function () { return getData().length; }, // length of data
    getData: function($defer, params) {
        var filteredData = getData();
        var orderedData = params.sorting() ?
                            $filter('orderBy')(filteredData, params.orderBy()) :
                            filteredData;

        $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
    },
    $scope: { $data: {} }
});

});

Any ideas welcomed!

Thanks, Kevin.


Solution

  • http://plnkr.co/edit/Q3GLxP55bGgVB7I28kbY?p=preview

     $scope.$watch("dataset", function () {
              $scope.tableParams.$params.page=1;
    
                $scope.tableParams.reload();
            });