I've searched SO and the web for a long time but still can't find the right answer to my problem. Although there are a lot of threads addressing function to Factory/Service conversion, none seem to apply to my current situation. I frequently use Services for setters/getters and $http calls without issue so I'm struggling to find out why I'm having so much trouble converting this simple function to a Factory or Service.
I have a table of data that I am paginating using the following code in my HTML:
<tr data-ng-repeat="book in filtered = (books | filter: query) | startFrom:currentPage*pageSize | limitTo:pageSize">
ng-show="showNext(filtered)"
$scope.showNext = function(filtered){
var numPages = Math.ceil($scope.data.length/$scope.pageSize),
lastPage = $scope.currentPage+1;
if(filtered.length > $scope.pageSize && lastPage < numPages){
return true;
}else if(filtered.length > $scope.pageSize && lastPage === numPages){
return false;
}else{
return false;
}
};
app.factory('PaginationService', function(){
var pagination = {};
pagination.showNext = function(data, pageSize, currentPage, filtered){
var numPages = Math.ceil(data.length/pageSize),
lastPage = currentPage+1;
if(filtered.length > pageSize && lastPage < numPages){
return true;
}else if(filtered.length > pageSize && lastPage === numPages){
return false;
}else{
return false;
}
};
return pagination;
});
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.showNext = function(filtered){
PaginationService.showNext(data, $scope.pageSize, $scope.currentPage, filtered);
}
this.showNext = function(data, pageSize, currentPage, filtered){
var numPages = Math.ceil(data.length/pageSize),
lastPage = currentPage+1;
if(filtered.length > pageSize && lastPage < numPages){
return true;
}else if(filtered.length > pageSize && lastPage === numPages){
return false;
}else{
return false;
}
};
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.showNext = function(filtered){
MyService.showNext(data, $scope.pageSize, $scope.currentPage, filtered);
}
Problem is in implementation in controller
$scope.showNext = function(filtered){
PaginationService.showNext(data, $scope.pageSize, $scope.currentPage, filtered);
}
Nothing is returned from $scope.showNext()
so in view it will always evaluate to undefined
Add return
so that the boolean returned by service function gets returned to the controller scope function
$scope.showNext = function(filtered){
return PaginationService.showNext(data, $scope.pageSize, $scope.currentPage, filtered);
}