Buccaneer Buccaneer - 4 months ago 78
AngularJS Question

AngularJS - Pagination Example with Logic like Google

I have tried to implement this paging solution that I found online from this link:

http://jasonwatmore.com/post/2016/01/31/AngularJS-Pagination-Example-with-Logic-like-Google.aspx

I think the issue is in the way the functions are called, because the setPage function gets called before I have all my data so it does not know how many total items there are to be displayed etc. Can someone take a quick look and see what I'm doing wrong?

function HistoryController($window, $scope, $modal, $state, toaster, PagerService, HistoryFactory, $timeout) {
var vm = this;

vm.uploads = [];
vm.includeCancelled = false;
vm.uploadDataModal = {};
vm.pager = {};

vm.setPage = setPage;

activate();

function activate() {
getHistory();
vm.setPage(1);
}

function setPage(page) {
if (page < 1 || page > vm.pager.totalPages) {
return;
}

// get pager object from service
vm.pager = PagerService.GetPager(vm.uploads.length, page);

// get current page of items
vm.items = vm.uploads.slice(vm.pager.startIndex, vm.pager.endIndex + 1);
}

function getHistory() {
HistoryFactory.getHistory(vm.includeCancelled).then(
function(response) {
_.each(response.data, function(upload) {
upload.inProgress = upload.status && ['INPROGRESS','NEW'].indexOf(upload.status.statusCd.trim()) > -1;
});
vm.uploads = response.data;

if($state.params.reupload){
uploadProductionData();
$state.params.reupload = false;
}
});
}

Answer

This is a very common mistake of not understanding asynchronous calls.

HistoryFactory.getHistory(vm.includeCancelled).then({}) is async, meaning that it will make the call and then continue executing code after the async call. When the async call has finished, the code inside .then({}) will then execute which could be 5 milliseconds or 5 seconds.

So here:

function activate() {
    getHistory();      // async call, doesn't wait
    vm.setPage(1);     // executed immediately after, data not ready 
}

Needs to be:

function activate() {
    getHistory();
}

And changegetHistory() to:

function getHistory() {
    HistoryFactory.getHistory(vm.includeCancelled).then(
        function(response) {
            _.each(response.data, function(upload) {
                upload.inProgress = upload.status && ['INPROGRESS','NEW'].indexOf(upload.status.statusCd.trim()) > -1;
            });
            vm.uploads = response.data;

            if($state.params.reupload){
                uploadProductionData();
                $state.params.reupload = false;
            }

            // Now call setPage after data is finished
            vm.setPage(1);
        });
}