Currently, I am developing a compact Contact application using Bootstrap 4 along with AngularJS v1.6.6.
This application is designed to showcase a JSON file containing various user data. Considering the large dataset in the JSON, the app features a pagination system for ease of navigation.
Initially, the pagination functioned as expected within the controller. However, upon attempting to convert it into a service, it ceased to work properly.
To view a working version with the pagination integrated within the controller, click HERE.
The current implementation comprises of:
// Defining an Angular module named "contactsApp"
var app = angular.module("contactsApp", []);
// Creating the controller for "contactsApp" module
app.controller("contactsCtrl", ["$scope", "$http", "$filter", "paginationService", function($scope, $http, $filter) {
var url = "https://randomuser.me/api/?&results=100&inc=name,location,email,cell,picture";
$scope.contactList = [];
$scope.search = "";
$scope.filterList = function() {
var oldList = $scope.contactList || [];
$scope.contactList = $filter('filter')($scope.contacts, $scope.search);
if (oldList.length != $scope.contactList.length) {
$scope.pageNum = 1;
$scope.startAt = 0;
};
$scope.itemsCount = $scope.contactList.length;
$scope.pageMax = Math.ceil($scope.itemsCount / $scope.perPage);
};
$http.get(url)
.then(function(data) {
// storing contacts array
$scope.contacts = data.data.results;
$scope.filterList();
// Incorporating Pagination Service
$scope.paginateContacts = function(){
$scope.pagination = paginationService.paginateContacts();
}
});
}]);
The service section contains:
app.factory('paginationService', function(){
return {
paginateContacts: function(){
// Pagination logic
$scope.pageNum = 1;
$scope.perPage = 24;
$scope.startAt = 0;
$scope.filterList();
$scope.currentPage = function(index) {
$scope.pageNum = index + 1;
$scope.startAt = index * $scope.perPage;
};
$scope.prevPage = function() {
if ($scope.pageNum > 1) {
$scope.pageNum = $scope.pageNum - 1;
$scope.startAt = ($scope.pageNum - 1) * $scope.perPage;
}
};
$scope.nextPage = function() {
if ($scope.pageNum < $scope.pageMax) {
$scope.pageNum = $scope.pageNum + 1;
$scope.startAt = ($scope.pageNum - 1) * $scope.perPage;
}
};
}
}
});
Incorporation within the view:
<div ng-if="pageMax > 1">
<ul class="pagination pagination-sm justify-content-center">
<li class="page-item"><a href="#" ng-click="prevPage()"><i class="<fa fa-chevron-left"></i></a></li>
<li ng-repeat="n in [].constructor(pageMax) track by $index" ng-class="{true: 'active'}[$index == pageNum - 1]">
<a href="#" ng-click="currentPage($index)">{{$index+1}}</a>
</li>
<li><a href="#" ng-click="nextPage()"><i class="<fa fa-chevron-right"></i></a></li>
</ul>
</div>
Confirming that the service file is appropriately included after the app.js
:
<script src="js/app.js"></script>
<script src="js/paginationService.js"></script>
As I am not proficient in AngularJS, could you guide me on what might be lacking?