Combine data from various requests in ng-repeat

I have a panel on my page displaying 6 categories fetched from an API call:

var getCategories = function (customUrl) {

    $http.get(customUrl).then(function success(response) {
        $scope.categories = response.data;
        // console.log($scope.categories);
        // ****
    },
    function error(response) {
        console.log("An error occurred in fetching categories", response)
    });
};

Within this request, there is an angular.forEach loop that sends an API request for each category individually

angular.forEach($scope.categories, function (category) {

    var queryString = '?categoryId=',
        url = urlData + queryString;

    var getArrayLength = function(url){
        $http.get(url)
            .then(function success(response) {
                $scope.getLength = response.data;
                console.log($scope.getLength)

            }, function error(response) {
                console.log("Error in obtaining length", response)
            });
    };

    getArrayLength(url + category.id);

    category.selected = $scope.selectedAllCat;
});

Currently, everything seems fine. The console log for $scope.getLength shows 6 different arrays and $scope.getLength.length returns the length of those arrays.

Now, I'm trying to display a table on my page like this:

<div class="panel-body">
<table class="table">
   <tr>
       <td class="col-md-1"><input type="checkbox" 
           ng-model="selectedAllCat"
           ng-click="selectAllCat()">&nbsp;</td>
       <td class="col-md-9">All</td>
       <td class="col-md-2">
           {{ initialDataLength.length }}
       </td>
   </tr>
   <tr ng-repeat="category in categories | orderBy : 'id' ">
       <td class="col-md-1">
          <input type="checkbox"
                 ng-model="category.selected"
                 ng-click="updateFilter(category.id)">&nbsp;
       </td>
       <td class="col-md-9">{{ category.name }}</td>
       <td class="col-md-2">
           {{ getLength.length }}
       </td>
    </tr>
</table>

This is where I'm facing an issue. How can I bind the array's length with the category name? Currently, it displays the same length for each category name. Thank you in advance.

Answer №1

To enhance performance, you can establish an object that links category ids to their respective lengths. This object can be populated with values after each request.

$scope.categoryLengths = {};
angular.forEach($scope.categories, function (category) {

    var queryString = '?categoryId=',
        url = urlData + queryString;

    var getArrayLength = function(url){
       $http.get(url)
           .then(function success(response) {
               $scope.getLength = response.data;
               $scope.categoryLengths[category.id] = response.data // Store category length
               console.log($scope.getLength)

            }, function error(response) {
                console.log("error in getting length", response)
            });
    };
    getArrayLength(url + category.id);

    category.selected = $scope.selectedAllCat;
});

Subsequently, display it as follows:

<td class="col-md-9">{{ category.name }}</td>
<td class="col-md-2">{{ categoryLengths[category.id] }}</td>

Answer №2

One way to connect the length property to your specific category object is by binding it directly.

angular.forEach($scope.categories, function (category) {
    var queryString = '?categoryId=',
    url = urlData + queryString;

    var getArrayLength = function(url){
    $http.get(url)
        .then(function success(response) {
            category.categoryLength = response.data.length;
            //console.log($scope.getLength)

        }, function error(response) {
            console.log("error in getting length", response)
        });
};
getArrayLength(url + category.id);
category.selected = $scope.selectedAllCat;
});

In addition,

<tr ng-repeat="category in categories | orderBy : 'id' ">
   <td class="col-md-1">
      <input type="checkbox"
             ng-model="category.selected"
             ng-click="updateFilter(category.id)">&nbsp;
   </td>
   <td class="col-md-9">{{ category.name }}</td>
   <td class="col-md-2">{{ category.categoryLength }} </td>
</tr>

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

The layout in Nextjs _app does not stay constant; it refreshes with each page change

After creating a _app.js file: const MyApp = ({Component, pageProps}) => { const getLayout = Component.getLayout || ((page) => <Layout>{page}</Layout>) return getLayout(<Component {...pageProps} />) } export default ...

The carousel in the Project file seems to be malfunctioning

Having previously utilized Owl carousel on my website, I made the switch to slick carousel for the slider on a NATA coaching center in Chennai. Unfortunately, I'm encountering issues with getting the slider to work and I'm unsure of where I may b ...

Implementing long polling for private messaging in PHP's chat functionality

Can you help me with a question I have regarding my chat form on the HTML page? Here is the code for the form: <form action="../addchat.php" method="POST" enctype="multipart/form-data"> <textarea id="textarea" style="border- ...

Implementing a Tab on Firefox Extension Upon Window Load

I have a requirement to add a tab whenever a new Firefox window is loaded for my bootstrap extension. Below is the code snippet I am using: var WindowListener = { setupBrowserUI: function(window) { window.gBrowser.selectedTab=window.gBrowser.a ...

Is there a way to retrieve and update the data of all the child elements within a table row dynamically?

I have a table with the following header information. <table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th> Date ...

Customize div background with an image captured by a camera

I am currently working on developing a mobile application using PhoneGap for Android. One of the tasks I am trying to accomplish is setting the background of a div element to the photo captured using the device's camera. The camera functionality is w ...

Removing a specific MySQL row using HTML in collaboration with Node.js

I've been working on a feature to allow users to delete specific rows from a table. Each row has a "Delete" link at the end, but when I click it, nothing happens. There are no errors displayed, and the console shows that 0 row(s) have been updated, ye ...

Parsing JSON data on the client side in an ASP.NET application

I am currently working with JSON data that looks like this: "Table":[ { "AF":2000.00 "RegionNumber":1 "RegionName":"Black Sea" }, { "AF":100.00 "RegionNumber":1 "RegionName":"Black Sea" }, { "AF":15000.00 "RegionNumber":2 "RegionName":"Ista ...

Struggling with syntax challenges while trying to loop through an array in Swift?

I am currently tackling the challenge of looping through an array of usernames in Swift, using Xcode. I have been struggling with the syntax and implementation. This is what I have so far: // Read text file if let filepath = NSBundle.mainBundle( ...

Is it possible to start a useState within a loop?

I am utilizing a React module designed for managing spreadsheets called react-spreadsheet. You can find it at this link: https://github.com/iddan/react-spreadsheet/ For my specific project requirements, I need to incorporate multiple spreadsheets with tab ...

Learn how to utilize Vue 3 to access properties that have been passed down from a parent component, even if they

Hey there, hope everything is going well. I'm familiar with react.js, but when I gave vue a try, things felt a bit different. In react, it's easy to access props passed from the parent in the child component without much hassle. However, in vue, ...

Arranging misshapen circles on the exterior of a sphere

My current project involves utilizing Three.js to position circles of various sizes evenly across the surface of a sphere, inspired by the concept seen in the periodic table of elements example. Despite extensive research efforts, I've come to the re ...

The top scrolling behavior on click applies exclusively to the first set of Bootstrap 5 tabs

I am experiencing an issue with my HTML webpage that contains multiple BS5 Nav Tabs. The first tab is not functioning properly, while all the other tabs are working smoothly. When I click on the first BS5 Nav Tab, the page scrolls to the top with the addre ...

Grouping JSON data in SQL Server

I need help converting my table data to JSON format Here is the structure of my table: DROP TABLE IF EXISTS #tmp CREATE TABLE #tmp(AnalyticGoodsT CHAR(6), date SMALLDATETIME) INSERT INTO #tmp(AnalyticGoodsT, date) VALUES ('000001', '202304 ...

Count, copy, and validate a group of spans using Protractor with AngularJS

As a beginner in automated testing, Protractor, and angularJS, I am looking for guidance on counting and verifying text in a list. The list contains items like Attractions, Capacity, and Content, which inform the user of their privileges. Here is the rele ...

Leveraging the import statement within lib.d.ts to enhance Intellisense functionality in Visual Studio Code

Looking to streamline my JavaScript project by utilizing custom global variables and harnessing the power of VSCode intellisense for auto completion. Here's what I'm aiming for: See example of auto completion for 'lol' After some sear ...

What are some ways to display multiple divs within a single popup window?

I am attempting to create the following layout: https://i.sstatic.net/OzE98.png Here is what I have been able to achieve: https://i.sstatic.net/7GxdP.png In the second picture, the divs are shown separately. My goal is to display the incoming data in a ...

"Error message encountered while trying to execute a GET HTTP request with incorrect JSON formatting

Currently, I am working on retrieving a list of users from our software. The goal is to format the names and email addresses of these users into a list for comparison with other data sets in order to determine accuracy. I have included the code snippet I a ...

What is the best way to retrieve environment variables from an NPM package in an Angular 5 application

Is there a method for my node module, created from an Angular 5 application, to access the environment variable from the Angular 5 application (environments/environment.ts)? Perhaps Angular 5 exports its environment variables to JavaScript global variables ...

Adjust the object size to match the Viewport dimensions

I've been developing a VR world where the camera can be turned and tilted in the center but not moved around freely. Within this virtual reality environment, you have the ability to attach a video to the background. Users can either play it by clicki ...