Implementing pagination within nested ng-repeat in Angular app

I am currently utilizing Angular along with the Material library in my project. I am facing an issue with two nested ng-repeat loops within md-tables. The problem lies in the fact that the variable is getting overridden with each request in the nested loops. Although I could combine the requests and iterate through them, the dynamic pagination feature would not be functional.

Below is the index file containing the tables:

<div ng-init="getCategories()" flex>
...
 <div class="content-main"  ng-repeat="category in categories">
...
    <md-content>
        <table md-table ng-init="getBooks(category.id)">
           ...
           <tr md-row ng-repeat="book in books | orderBy: query.order ">
                <td md-cell>
                    <span>{{ book.title }}</span>
                </td>
    ...
    </md-content>
    <md-table-pagination md-limit="query.limit"
                         md-limit-options="limit"
                         md-page="query.page"
                         md-page-select="options.pageSelect"
                         md-total="{{booksCount}}"
                         md-boundary-links="options.boundaryLinks">
    </md-table-pagination>

Here are the simplified Angular controller functions:

$scope.getCategories = function () {
 \\perform get request
  $scope.categories = resp.data.rows;
  }

$scope.getBooks = function () {
 \\perform get request with pagination and search parameters
   $scope.books = resp.data.rows;
   $scope.booksCount = resp.data.amount;
  }

As a result, every request to getBooks overrides the "books" variable, causing, for example, the issue of seeing the same books (from category 2) for both categories.

Category 1
 Book C Book D
Category 2 
 Book C Book D
(incorrect)

However, I should actually have different books for Category 1:

Category 1
 Book A Book B
Category 2 
 Book C Book D
 (correct)

Answer №1

The reason for the issue you are facing is due to the presence of an ng-init within your ng-repeat block. This causes the $scope.books to be set for each iteration, with the last one overwriting all previous instances of $scope.books.

To resolve this issue, I suggest making the following changes to your code:

  • Instead of using ng-init within the ng-repeat, call the getBooks function directly from the success callback inside the getCategories function. It is not recommended to use ng-init as it is considered a bad practice. Here is an example of how you can modify your code:

    $scope.getBooks = function (categoryId) {
      // make a get request with pagination and search parameters
      $scope.books[categoryId] = resp.data.rows;
      $scope.booksCount[categoryId] = resp.data.amount;
    }
    
    $scope.getCategories = function () {
      // make a get request
      $scope.categories = resp.data.rows;
      $scope.books = {};
      $scope.booksCount = {};
      $scope.categories.forEach(function(category) {
        $scope.getBooks(category.id)
      })
    }
    
    $scope.getCategories();
    
  • Your HTML code should look like this after the modifications:

    <div flex>
    ...
    <div class="content-main" ng-repeat="category in categories">
    ...
      <md-content>
        <table md-table>
        ...
          <tr md-row ng-repeat="book in books[category.id] | orderBy: query.order">
            <td md-cell>
                <span>{{ book.title }}</span>
            </td>
            ...
      </md-content>
    

This solution should work well, unless there are any errors present in the code that were not provided for verification.

Answer №2

To start, make sure to update your controller code as shown below:

 $scope.fetchCategories = function () {
            // Perform a GET request
            $scope.categoriesList = response.data.rows;
            angular.forEach($scope.categoriesList, function (category, index) {
                $scope.retrieveBooks(category);
            });
        }();

        $scope.retrieveBooks = function(category) {
             // Make a request using the category.id.
            // GET request with pagination and search parameters
            $scope.categoryData = response.data;

        };

Next, tweak your HTML structure as follows:

<div flex>
...
 <div class="content-main" ng-repeat="category in categoriesList">
...
    <md-content>
        <table md-table>
           ...
           <tr md-row ng-repeat="book in category.rows | orderBy: query.order ">
                <td md-cell>
                    <span>{{ book.title }}</span>
                </td>
    ...
    </md-content>

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

I'm curious about the distinction between React's one-way data binding and Angular's two-way data binding. Can someone please clarify the key differences

My understanding of these concepts is a bit hazy. If I were to develop the same ToDo application using AngularJS and ReactJS, what exactly distinguishes React ToDo's use of one-way data binding from AngularJS's two-way data binding? From what I ...

Issues with jQuery function arising post-update to newer jQuery version

Recently, I encountered an issue with a function that used to work perfectly fine with jQuery 1.8.3. However, when I upgraded to jQuery 1.10.x or above, the function stopped working. <script type="text/javascript"> $.ajaxSetup({cache: false}); ...

Are there equivalent npm variables like (`npm_config_`) available in yarn console scripts?

Utilizing variables in custom npm commands is possible (example taken from ): { "scripts": { "demo": "echo \"Hello $npm_config_first $npm_config_last\"" } } Can this functionality also be achieved ...

tips for efficiently loading JSON files using Angular

I currently have a situation where multiple controllers are calling the method getData() from a service. To prevent unnecessary duplicate http calls for the same json file, I have implemented the following approach: QuizApp.service('quizService' ...

Crafting a robust and secure password using Yup and Formik while receiving personalized error notifications

My Password Validation Dilemma I'm in the process of developing a password field that can assess the strength of the input provided. In a different response, I came across a regex that I could utilize to validate whether the input meets specific crit ...

Filter an object in Typescript and retrieve a single key

Managing a set of checkboxes is essential in assigning roles to new users. While it's possible to filter and retrieve only the checked checkboxes, extracting just the "name" key poses a challenge. The current method involves filtering with a for loop ...

Retrieve the ID of a specific row within a table in a datatables interface by selecting the row and then clicking a button

My goal is to have a table displayed where I can select a row and then have the option to edit or delete that row with a query. To achieve this, I need a primary key that won't be visible to the user. This is how my table is set up: <table id=&apo ...

The functionality of Angular.js route seems to be malfunctioning

Hello friends, I am fairly new to working with AngularJS and have been experimenting with angular Route. However, I encountered an issue where clicking on #/home resulted in a strange URL appearing here. Oddly enough, the default otherwise condition seems ...

Adjusting the array when items in the multi-select dropdown are changed (selected or unselected)

I am looking to create a multi-select dropdown in Angular where the selected values are displayed as chip tags. Users should be able to unselect a value by clicking on the 'X' sign next to the chip tag, removing it from the selection. <searcha ...

Timeout during the beforeLoad event

I am currently working on writing some ExtJS 4 script and have come across the following code: var companyStoreModel = Ext.create('Ext.data.Store', { model: 'CompanyDataModel', proxy: { type: 'ajax&apos ...

Encountered an Error with My Protractor Script - Object Expected

Currently, I am in the process of learning automation testing for an AngularJS application. However, I have encountered an "object expected" error on line 4, which is pointing to the first line of my script. describe("Homepage", function() { it("Navig ...

(Is it even necessary to use a timezone library for this straightforward scenario?)

As I delve into the realm of time zones for the first time, I've heard tales of how challenging it can be for developers. To ensure I am on the right track, I am posing this question as a safeguard to make sure nothing is overlooked. My scenario is q ...

The feature of determining if an edge exists, within the dagre-d3/graphlib,

Has anyone utilized the graph.hasEdge function in dagre-d3/graphlib to check for the existence of an edge between two nodes? This API takes two arguments representing the two nodes and verifies if there is an edge connecting them. I am facing an issue whe ...

What is the process for retrieving the result of a promise at a later time?

var screencastId = 'abc' var a = youtube.get(screencastId); a.then(function(screencast) { // Great, the screencast information is now available. console.log(screencast); }); // How can I access the `screencast` variable below? connection.be ...

Limit the amount of data possible to input in the HTML editor using AngularJS

Here is the data obtained from the API: <style type="text/css> <!--td {border: 1px solid #ccc;}br {mso-data-placement:same-cell;}--> </style> <span style="font-size:11pt;font-family:Calibri,Arial;font-style:normal;color:#000000;" ...

Encountering 404 Error in Production with NextJS Dynamic Routes

I'm currently working on a next.js project that includes a dynamic routes page. Rather than fetching projects, I simply import data from a local JSON file. While this setup works well during development, I encounter a 404 error for non-existent pages ...

Compatibility issues between XMLHttpRequest and curl

Today, I am attempting to create a small XHR in JavaScript, Java, and C#, but it's not working for some reason... Below is the code snippet: var xhr = new XMLHttpRequest(); function init(){ xhr.open("POST","http://www.opsu.gob.ve/portal/controles/ ...

Issue with two Jquery slider forms

Within a Jquery slider, I have implemented two distinct forms (using this specific Jquery slider: http://tympanus.net/Tutorials/FancySlidingForm/) . My goal now is to establish JavaScript/jQuery validation for these two forms separately BASED on the form ...

Optimizing Static File Caching in Yii

Having a frustrating issue with Yii where my local development environment caches CSS and JS files. Despite making changes to the file, the edits do not reflect in the output and sometimes causes corruption leading to broken functionality. This problem see ...

overlay appears as I reveal the slide-out menu

Struggling with adding an overlay to an expanding navigation bar, similar to Youtube's overlay when the slide-out nav is open. Need help with the implementation. Here is the javascript code for the expanding navigation using jQuery: 'use strict ...