I am currently working with an array called $scope.results
which contains 8 objects. I have also created a custom simple pagination and a function called selectAll()
that I'm trying to get to work together.
Please refrain from suggesting the use of bootstrap pagination for angularjs as I have built my own solution that meets my requirements.
$scope.results = [
{
"devID": "1",
"devName": "item 1",
"desc": "sample desc"
},
{
"devID": "2",
"devName": "item 2",
"desc": "sample desc"
},
{
"devID": "3",
"devName": "item 3",
"desc": "sample desc"
},
{
"devID": "4",
"devName": "item 4",
"desc": "sample desc"
},
{
"devID": "5",
"devName": "item 5",
"desc": "sample desc"
},
{
"devID": "6",
"devName": "item 6",
"desc": "sample desc"
},
{
"devID": "7",
"devName": "item 7",
"desc": "sample desc"
},
{
"devID": "8",
"devName": "item 8",
"desc": "sample desc"
}
];
In addition, there is an empty object named $scope.deleteList = {}
which gets populated with IDs by the selectAll()
function.
Here is the code for my $scope.selectAll()
along with some console logs for debugging:
$scope.selectAll = function(){
$scope.resultsToDelete = $scope.results.slice(($scope.currentPage * $scope.pageSize), $scope.pageSize);
console.log("$scope.results:", $scope.results);
console.log("$scope.currentPage:", $scope.currentPage);
console.log("$scope.pageSize:", $scope.pageSize);
console.log("$scope.currentPage * $scope.pageSize:", ($scope.currentPage * $scope.pageSize));
for (var i = 0; i < $scope.resultsToDelete.length; i++) {
var item = $scope.resultsToDelete[i];
$scope.devDelList[item.devID] = true;
}
};
The expression
($scope.currentPage * $scope.pageSize)
gives me the index of the first object on the next page in the list.
Below is the implementation of my pagination logic:
$scope.pagination = function(itemList) {
$scope.currentPage = 0;
$scope.pageSize = 4;
$scope.numOfPages = Math.ceil(itemList.length / $scope.pageSize);
$scope.pageNumbersArray = [];
for (var i = 0; i <= $scope.numOfPages - 1 ; i++) {
$scope.pageNumbersArray.push(i);
}
}($scope.results)
$scope.prev = function() {
if ($scope.currentPage > 0) {
$scope.currentPage = -- $scope.currentPage;
}
}
$scope.next = function() {
if ($scope.currentPage < $scope.numOfPages - 1 ) {
$scope.currentPage = ++ $scope.currentPage;
}
}
$scope.goToPage = function(pageNum) {
$scope.currentPage = pageNum;
}
My problem lies in the usage of the .slice()
method on the results array. It works correctly only for the first page when $scope.currentPage = 0
. However, once $scope.currentPage = 1
, the $scope.results.slice()
call returns an empty array.
$scope.results.slice(0, 4)
provides the correct IDs for the first page containing 4 items.
$scope.results.slice(4, 4)
returns an empty array (i.e., []), failing to retrieve the second set of 4 items.
What could be causing this issue?