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

There seems to be a glitch with the functionality of the HighStocks Tooltip

I've implemented a modified version of the example from highcharts: $(function () { $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) { // Create the chart $('#co ...

Detect the "@" character through keyUp for the implementation of @mentions feature

I am currently working on implementing an @mention feature using Vue and Vanilla JS, but I am facing issues with targeting the "@" character specifically. Within my template: <trix-editor ref="trix" @keyup="listenForUser" ></trix-editor& ...

Modify a CSS style with JavaScript or jQuery

Can CSS rules be overwritten using jQuery or JavaScript? Imagine a table with rows categorized by different classes - "names" for persons and "company" for companies. How can we efficiently hide or show specific rows based on these classes? If we have a ...

Include category to the smallest element

I am attempting to use JQuery to find the height of the tallest element and then add that height to other elements that are shorter. My goal is to assign the class, main-nav-special-padding, to these shorter elements using my current JQuery code. I tried t ...

Having difficulty retrieving the value of a dynamically selected radio button in AngularJS

Having trouble with selecting radio options in my code, need some assistance to fix it. Check out my Plnkr Code - http://plnkr.co/edit/MNLOxKqrlN5ccaUs5gpT?p=preview Although I am able to retrieve names for the 'classes' object, the selections ...

Methods for establishing state within a React Native render function

I encountered an issue when attempting to set state within the render lifecycle. Warning: It is not recommended to update state during an ongoing state transition, such as in the render method or another component's constructor. The render method s ...

Is it possible to retrieve the ID of an anchor tag when the text within two table items meets my specified criteria?

In the table with ID "PTSRCHRESULTS," each row contains anchor links. I am trying to find the ID of an element within a row that contains both "Undergrad" and "1". This is for Power Automate Desktop, but I can use JavaScript to get the necessary ID to clic ...

Incorporate a Variety of Elements onto Your Webpage

I have developed a custom tooltip plugin using JQuery, and I am implementing it on multiple A tags. Each A tag should have a unique tooltip associated with it, so I have the following code: var $tooltip = $("<div>").attr("id", tooltip.id).attr("cla ...

Verifying numerous route paths using Vue's dynamic binding (v-bind)

Currently, I am assigning a class to an li element depending on the route path using this code snippet: <li v-bind:class="{ 'current': $route.path == '/services' }"><nuxt-link to="/services">Services</ ...

Expanding and shrinking the index within a specific circular boundary in JavaScript

I'm dealing with a circular range of ASCII values from a to z, where each letter corresponds to a number between 97 and 122. I have no issue with increasing the value within this range, but I am struggling when it comes to decreasing it. For example ...

Is it true that outerHeight(true) excludes margins?

As stated in the JQuery documentation, the outerHeight(true) function should return the complete height of an element, including padding, border, and margins. However, I encountered a scenario where this functionality seemed to be flawed. You can find a co ...

Leveraging the power of AngularJS and Bootstrap, create a vertical nested tab interface that dynamically

After successfully creating a Dynamic Tab using AngularJS with Bootstrap, I decided to add Sub Tabs under one of the tabs dynamically. While this feature is working fine, I encountered an issue when trying to move to another main tab and then returning to ...

How can I extract the URL from the event listener in Cordova's in-app browser event and then automatically close it once a specific URL is reached?

In my journey with ionic version 1 (just starting out with ionic & angularjs), I encountered an issue while trying to close the in app browser upon reaching a specific URL. The problem arises from the fact that the event triggered on "loadstart" is o ...

Utilizing JavaScript text variables as hidden inputs

My JavaScript code is responsible for populating a modal from various sections of a website. Essentially, when the modal expansion button is clicked, it collects all data associated with that particular button press. While this functionality works flawles ...

A guide to sending props to a CSS class in Vue 3

I need to develop a custom toast component that includes a personalized message and class. While I have successfully passed the message as props, I am encountering difficulties in applying the bootstrap class. Component File: Toast.vue <script ...

Angular $watch function not reflecting changes in the user interface

My $watch function is updating the model, but the bound controls in the UI are not reflecting the changes. Here is a screenshot of the updated model. https://i.stack.imgur.com/0ISg5.png The UI code looks like this: <form method="post" action="" role= ...

`Is it common to use defined variables from `.env` files in Next.js applications?`

Next.js allows us to utilize environment variable files such as .env.development and .env.production for configuring the application. These files can be filled with necessary environment variables like: NEXT_PUBLIC_API_ENDPOINT="https://some.api.url/a ...

Resetting input field based on callback function

In my simple script, I have two pages - script.php and function.php. The script.php page contains an input field with the ID #code, a link with the ID #submit, and a jQuery function. $('#submit').click(function () { $.ajax({ url: 'f ...

Processing MongoDB elements in NodeJS by retrieving them and appending them to a list or array for further processing

Currently, I am involved in a full stack project that requires fetching stock data from mongodb and performing algorithms on specific information. Here is an illustration of the JSON object stored in mongodb: [{ _id: 5e11d67abf05f3d00d56b801, LUNA: { ...

Setting up webRTC and Express.js to function within the same domain requires proper configuration

Currently, I am in the process of creating a video conferencing website using node.js and express.js rather than apache. However, I am faced with some challenges when deciding on the best approach. The main goal is to have the server deliver the website t ...