Search code examples
angularjspagination

Angular pagination - update data onclick


I'm attempting to implement pagination on a angular/bootstrap site. I have the data showing with the correct # of per-page rows, I have the angular paging showing the right number of pages...but heck if I can find anywhere that tells me HOW to use the paging to refresh my data when a page # is clicked...?! {{currentPage}} is updating, but not sure how to have it call getPresentations to update the list.

<div>
        {{noOfPages}} &nbsp; {{currentPage}} &nbsp; {{maxSize}}
        <pagination num-pages="noOfPages" current-page="currentPage"></pagination>
    </div>

<script type="text/javascript">
    angular.module('app', ['ui', 'shared', 'ui.bootstrap']).controller('AppCtl', function ($scope, $http, $window) {
        var mvc = $window.MVC;
        $scope.noOfPages = 0;
        $scope.currentPage = 1;
        $scope.maxSize = 5;

        $scope.getPresentations = function () {
            $http.get(mvc.base + "API/Presentations?page=" + $scope.currentPage + "&itemsPerPage=10")
               .success(function (result) {
                   $scope.presentations = result.Items;
                   $scope.noOfPages = result.TotalPages;
                   $scope.currentPage = result.Page;
               })
                .error(function (result, status) {
                    $scope.newModal.errors = mvc.getApiErrors(status, result);
                });
        };

        $scope.getPresentations();
    });
</script>

Solution

  • You've got 2 options:

    • $watch the current-page property
    • use the onSelectPage callback

    Here is the relevant page with $watch

      $scope.$watch('currentPage', function(newPage){
        $scope.watchPage = newPage;
        //or any other code here
      });
    

    And here one using the callback:

    $scope.pageChanged = function(page) {
        $scope.callbackPage = page;
        $scope.watchPage = newPage;
      };
    

    used like:

    <pagination on-select-page="pageChanged(page)" num-pages="noOfPages" current-page="currentPage"></pagination>    
    

    And finally the working plunk showing the 2 approaches: http://plnkr.co/edit/UgOQo7?p=preview