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"><</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">></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?