0

I'm designing a custom pagination directive for Angular 1, but the data binding doesn't seem to work correctly. The currentPage property seems to update without an issue, but my numberOfPages property doesn't seem to update in the DOM. Furthermore, I have a next and previous button which are disabled based on the current page, but only one of their expressions appears to be evaluated correctly. Here is my code:

My Directive:

angular.module('testModule').directive('pagination', ['_', function(_) {
return {
  restrict: 'E',
  templateUrl: 'templates/pagination.html',
  scope: {
    currentPage: '=',
    numberOfPages: '@',
    onPageSelected: '&',
  },
  controller: function($scope){
    $scope.pageNumbers = [1];

    $scope.$watch('numberOfPages', function(){
      if($scope.numberOfPages > 1){
        $scope.pageNumbers = _.range(1, $scope.numberOfPages);
      }
      else{
        $scope.pageNumbers = [1];
      }
    })

    $scope.selectPage = function(pageNo){
      if(pageNo < 1){
        $scope.currentPage = 1;
      }
      else if(pageNo >= $scope.numberOfPages){
        $scope.currentPage = $scope.numberOfPages;
      }
      else {
        $scope.currentPage = pageNo;
      }

      $scope.onPageSelected()($scope.currentPage);
    }
  }
};
}]);

My Template:

<div>
<button class="paginationTab" ng-click="selectPage(currentPage - 1)" ng-disabled="currentPage <= 1">&#60;</button>
<button ng-repeat="pageNo in pageNumbers track by pageNo"
        ng-class="pageNo == currentPage ? 'selected paginationTab' : 'paginationTab'" 
        ng-click="selectPage(pageNo)">
    {{pageNo}}
</button>
<button class="paginationTab" ng-click="selectPage(currentPage + 1)" ng-disabled="currentPage >= numberOfPages">&#62;</button>
</div>

currentPage and numberOfPages should both be numbers. onPageSelected is a function that takes a page number as an argument. I'm using npm to load angular v1.7.2 and underscore v1.9.1.

The Directive in use:

<pagination current-page="currentPage" number-of-pages="numberOfPages()" on-page-selected="onPageSelected"></pagination>

I can't understand why this code doesn't work as expected (there should be a button for each page but there isn't, and the 'next' button is never disabled no matter how far above the maximum number of pages you go). Can anybody see what's wrong with this directive?

John Riley
  • 468
  • 1
  • 6
  • 23
  • 2
    Can you show us the 3rd piece where you invoke it in a view? – BShaps Jul 09 '18 at 23:23
  • In markup camel case becomes a hyphenated word. So you're probably using in the call of the directive something as: `currentPage` when you should be using `current-page`. If it's not the case let me know. – Luiz Carlos Jul 10 '18 at 01:03
  • Added the call I'm using in my code to the original description. I managed to avoid the currentPage/current-page pitfall this time. – John Riley Jul 12 '18 at 14:33

0 Answers0