Search code examples
javascriptangularjssmart-table

Smart Table: set page programmatically


I'm using Smart Table and want to jump to a specific page once the controller is created and the table is displayed.

I found this snippet of code to do this programatically here on stackoverflow:

angular.element( $('#pagination') ).isolateScope().selectPage(pageNumber);

"pagination" is the HTML id of my Smart Table's pagination div. I can't call this until the controller exits as isolateScope returns "undefined". So I thought I'd call it a few milliseconds afterwards to ensure the table/page has been fully created.

selectPage works from my custom pagination, it works if I call it from a button at the bottom of the page, but NOT if it is called from a timer. I've traced the source into Smart Tables selectPage() and pipe() functions and I can't see the difference - one works, and the other doesn't.

See the Plunker: Press one button and it will jump to Page 5 as expected. Press the other button to set a 3s timer which should jump to page 2, and nothing happens...


Solution

  • Apparently, there's a better way for communicating with smart-table from the 'outside'.

    If you move the st-table directive to an outer div (in this case to the body):

    <body ng-controller="mainCtrl" st-table="displayed">
    

    then we can create a directive that will require the plugin's controller and use its functions:

    app.directive('handlePagination', function ($timeout) {
        return {
            require: '^stTable',
            restrict: 'AE',
            transclude: true,
            template: '<button class="btn btn-success btn-xs" ng-click="" ng-transclude></button>',
            scope: {
              goToPage: '@',
              delay: '@'
            },
            link: function link(scope, element, attrs, controller) {
                scope.delay = scope.delay || 0;
                element.on('click', function() {
                  var page = scope.goToPage; 
                  if (page > 0 && page <= controller.tableState().pagination.numberOfPages) {
                    $timeout(function() {
                       controller.slice((page - 1) * controller.tableState().pagination.number, controller.tableState().pagination.number);
                    }, scope.delay) 
                  }
                })
            }
        };
    });
    

    see this plnkr