In AngularJS, enhance pagination loading by appending a $resource queried array to the end of another

I'm currently working on implementing a loading feature for my Angular application. The goal is to preload page 3 when a user navigates to page 2.

Utilizing $resource, I'm querying the Posts resource using Post.query(). By calling Post.query({page: 1}), I retrieve an array of post records ranging from ID 0 to 9.

In my Post controller, I've set up parameters to specify the page like so: posts.json?page=1, where each page contains 10 posts.

The key objective is to load and combine pages 1 and 2 upon initial load, storing them in $scope.visiblePosts. Once a user reaches page 2, I want to fetch page 3 in the background and append it to $scope.visiblePosts.

For pagination, I've implemented the following code:

View:

<div ng-repeat="post in filtered = visiblePosts |
 startFrom:(currentPage-1)*pageSize | limitTo:pageSize | orderBy:order:true">

App:

app.filter("startFrom", function() {
  return function(input, start) {
    if (input) {
      start = +start;
      return input.slice(start);
    }
    return [];
  };
});

Controller:

$scope.currentPage = 1;

$scope.pageSize = 10;

$scope.noOfPages = Math.ceil($scope.posts.length / $scope.pageSize);

$scope.noPrev = function() {
  return $scope.currentPage === 1;
};

$scope.noNext = function() {
  return $scope.currentPage === $scope.noOfPages;
};

$scope.prevPage = function() {
  return $scope.setPage($scope.currentPage - 1);
};

$scope.nextPage = function() {
  return $scope.setPage($scope.currentPage + 1);
};

$scope.setPage = function(pageNo) {
  return $scope.currentPage = pageNo;
};

$scope.filter = function() {
  return window.setTimeout((function() {
    return $scope.noOfPages = Math.ceil($scope.filtered.length / $scope.pageSize);
  }), 10);
};

$scope.$watch("currentPage", $scope.setPage);

Any assistance would be greatly appreciated as I have tried various methods such as using concat() without success.

Answer №1

To begin with, it is important to refrain from altering your scope outside of the Angular digest cycle. Instead of using setTimeout and setInterval, opt for the built-in services $timeout and $interval. In this scenario, consider utilizing $evalAsync: AngularJS : $evalAsync vs $timeout

Furthermore, the statement

$scope.$watch("currentPage", $scope.setPage)
does not seem logical to me.

Lastly, regarding the main issue: the controller (and consequently the scope) gets instantiated each time you navigate to a new page, resulting in an inability to retain data across different pages within the scope.

In contrast to controllers, services are singletons, created only once and persist throughout the application lifetime.

A potential solution would be to develop a service that stores preloaded posts and loads subsequent pages ahead of time. Subsequently, the controller can request the required page content from this service.

This approach also eliminates the necessity for filters.

You can explore utilizing a cache feature from $cacheFactory to store the data or leverage the cache option offered by the $resource service. Following this method, after displaying the current page, preload the subsequent page so that it can be swiftly retrieved from the cache during the next access.

Example:

function MyController($scope, $resource) {

    var res = $resource("/posts.json", {}, {
        query: {
            method: 'GET',
            isArray: true,
            // enable caching:
            cache: true
        }
    });

    $scope.currentPage = 1;

    $scope.$watch("currentPage", function() {
        $scope.posts = res.query({
            page: $scope.currentPage
        });
        // precache the next page:
        res.query({
            page: $scope.currentPage + 1    
        });
    });

}

...

<div ng-repeat="post in posts">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Make the switch from using jQuery MouseEvent to utilizing AngularJS for a more

Presently, in my Angular directive within the link function, I am using the following code: (This directive is placed at a top level in the dom.) $(document).on("mousedown", ".resizer", function (e) { e.preventDefault(); resizing = true; frame ...

Tips for seamless communication between PHP and JavaScript

While working on my revolutionary WebIDE, I encounter numerous questions that challenge me. The goal of this project is to assist users in quickly developing what they normally would, but automated. One particular question I have is regarding the implement ...

Angular URL containing dynamic path parameters

I am looking to update the Angular URL to /jobs/id. I have written the code below, but I'm unsure if it will work: $location.path("/JobHire/jobs/"+response.data.id); How should I set up the route configuration? Currently, I have it configured like t ...

Tips on finding a JavaScript file using Google search

After releasing my jQuery plugin, I've noticed an increase in downloads. However, I'm curious to know where exactly it is being utilized. One idea I had was to search for the .js or .css file, potentially even looking at folder names. Is there a ...

Is incrementing x by 1 equivalent to x + 1?

I have a very basic angular application. It simply increases the value by 1 when clicked on using ng-click. Take a look at JSFiddle <div ng-app="app" ng-controller="ctrl"> <div ng-click="hello=hello+1">THIS WORKS ON CLICK: {{hello}}</d ...

Dynamically created HTML elements have no events attached to them in Angular and jQuery

Utilizing jQuery, I am dynamically generating new elements within an Angular Form that has been constructed using a Template Driven Forms approach. Despite successfully creating the dynamic elements, they do not seem to be assigned events/callbacks due to ...

There is currently no graph being shown

I've run this code but I'm not getting any output. There are no errors showing up, but I can't seem to figure out what's wrong. Can someone help me identify the issue? Thanks! <!DOCTYPE html> <html> <head> <m ...

Vue.js - When Property is Undefined and How to Render it in Browser

My experience with Vue has been quite puzzling. I've encountered an issue while trying to render a nested property of an object called descrizione, and although it does work, I keep receiving a warning from Vue in the console: TypeError: Cannot rea ...

Tips for resolving the error message "cannot read property of undefined"

I've been working on coding a Discord bot and I keep encountering an error when trying to check if "mrole" has the property "app". It's not functioning as expected and I'm puzzled by why this is happening. My intention is to retrieve the te ...

Leveraging AngularJS for retrieving the total number of elements in a specific sub array

I'm currently working on a to-do list application using Angular. My goal is to show the number of items marked as done from an array object of Lists. Each List contains a collection of to-dos, which are structured like this: [{listName: "ESSENTIALS", ...

Is there a way to prevent redundancy when exporting functions in Node.js?

Is there a way to avoid repeating module.exports or usuariosControllers when writing a small API in express for fun? module.exports.getUsuarios = (request, response) => {}; module.exports.crearUsuario = (request, response) => {}; module.exports. ...

React JS: Incorporating Multiple Placeholder Objects within Components

Apologies if this question is a duplicate, but I haven't found any helpful answers yet. I'm new to React and JavaScript. I am looking to include multiple objects inside a component: For example: src={url} name={text} subTitle={subtext} My in ...

pictures in photo display

Please check out my codepen project: html code: <body> <div class="thumbnails"> <a href="#"><img src="http://s30.postimg.org/4yboplkxd/dotty.jpg" width="100" height="100"></a> <a href="#"><img src="http:// ...

Develop a JavaScript library for use in the npm ecosystem

I have developed a minimalist JavaScript library that includes common functions: !!window.JsUtils || (window.JsUtils = {}); JsUtils = (function () { "use strict"; return { randomHex: function (len) { var maxlen = 8; ...

how to share global variables across all components in react js

Operating a shopping cart website requires transmitting values to all components. For instance, when a user logs into the site, I save their information in localStorage. Now, most components need access to this data. My dilemma is whether I should retriev ...

Is there a way to capture the click event of a dynamically generated row within a panel?

Could you please advise on how to capture the click event of a row that is generated within a panel? I have successfully captured events for rows generated on a page using the , but now I need assistance with capturing events from rows within a panel. I c ...

What is the best way to split strings in an input field?

My task is to create a form with an input field and a dropdown list containing options for Checkbox and Radio. The user should enter text in the input field and select a type from the dropdown. For example: Input field: One, Two, Three Radio The expecte ...

Troubleshooting RXjs problems on Heroku deployment

I've encountered an issue with my NodeJS/Angular2 website. It functions smoothly on my local Windows 10 setup, but when I attempt to deploy it on Heroku and access the site, the front-end console in Chrome displays an error message and the site fails ...

Changing the MIME type of a JavaScript file in a Jade/Pug environment to text/html

Hi there, I've been experimenting with jade/pug to get my node.js backend to render the front-end pages. However, I'm facing some issues when trying to include JavaScript for certain functionalities. Whenever I try to load it, I encounter this er ...

What is the most effective way to prevent JavaScript from running during page load or when the document is ready

I am facing a challenge with my asp.net page. Whenever a textbox is left empty, I want to hide the entire page from the code behind. The issue arises because there is javascript and jquery code that runs on document ready, accessing data from certain page ...