AngularJS: Retrieve individual objects from an array and subsequently initiate asynchronous requests

I am working with two tables, Category and Products, linked by a 1-N cardinality relationship.

https://i.sstatic.net/e6C2y.png

My goal is to retrieve all products belonging to a specific category.

https://i.sstatic.net/yDrjr.png

Here is the HTML table structure:

<tr ng-repeat="category in categories">
    <td>{{category.id}}</td>
    <td>{{category.name}}</td>
    <td>{{products[category.id]}}</td>
</tr>

The challenge lies in merging the 'categories' array with another function within the controller to handle asynchronous requests for each category.

app.controller("appController", function($scope. $http, getCategoriesService){

    // Retrieve all categories here
    $scope.categories = getCategoriesService.query();

    // Function to handle fetching products based on category
    function getCategoryProducts(category){
        $http("getProductsByCategory/"+category.id)
        .success(function(data){
            $scope.product[category.id];
        })
        .error(function(status){
            console.log(status)
        })
    }
});

app.factory("getCategoriesService", function($resource){
    return $resource("categories", {}, {
        listCategories: {
            method: "GET",
            isArray: true
        }
    })
})

Any suggestions or ideas on how to approach this?

Answer №1

An effective way to manage everything in your HTML is by utilizing a second ng-repeat that specifically filters products based on the current category. See example code below:

<tr ng-repeat="category in categories">
  <td>{{category.id}}</td>
  <td>{{category.name}}</td>
  <td>
    <table>
      <tr ng-repeat="product in products | filter: {categoryId: category.id}">
        <td>{{ product.name}}</td>
        </tr>
    </table>
  </td>
</tr>

For a visual demonstration, you can check out this live example.

Answer №2

After organizing your categories, why not implement a loop like this:

categories.forEach(
  category => retrieveProducts(category);
);

The function retrieveProducts() would look something like this:

function retrieveProducts(category){
        $http("fetchProductsByCategory/"+category.id)
        .success(function(data){
            $scope.product[category.id];
        })
        .error(function(status){
            console.log(status)
        })
    }

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

What is the reason behind JavaScript subtracting the timezone offset for ISO dates when passed into the Date() function?

In my function, I handle different valid date strings to produce a JavaScript Date object. Most strings work as expected, however, when an ISO formatted date (YYYY/MM/DD) is provided, the user's timezone offset is deducted from the date. For example ...

Using spin.js instead of an animated gif provides a sleek and modern alternative for adding loading

Seeking guidance as a newcomer to JQuery. A form "processing" div should appear after form submission. Currently, using a basic div with an animated gif for visual feedback: <div id="loading">Please wait, your news is being submitted... <img src= ...

how to show an error in a modal window when encountering an error

Using Blazor and Blazorstrap, typically when the server disconnects, an "Error" message is displayed. However, with the BsModal from Blazorstrap, it appears in the background layer, making it unresponsive. How can this be fixed? Is it possible to close the ...

Looking for arrays with duplicate values across multiple elements - a comprehensive guide

I need assistance with a PHP script that retrieves arrays where the values of specific fields are identical. Below is the code I have so far, but as I am new to PHP development, any guidance would be appreciated. Code: foreach($leads_details->resul ...

Experiencing a problem with my JavaScript code in Node.js due to an asynchronous issue arising when using a timeout

My goal with this code is to retrieve JSON questions and present them to the user through the terminal. The user has 5 seconds to respond to each question before the next one appears. However, I encountered an issue where the next question times out automa ...

Preventing unfiltered text input in Angular UI-Select

Lib link : https://github.com/angular-ui/ui-select Is there a way to prevent user input in a multiSelect? I want users to only be able to clear previously selected data, But how can I restrict them from entering any new text in the ui-select field? http ...

Transferring information to a controller using ajax in ASP.NET Core

I am encountering an issue with sending data to the controller through ajax. The value goes as "null". Can someone please assist me with this? Here are my HTML codes: <div class="modal fade" id="sagTikMenuKategoriGuncelleModal" data ...

Submit a single data value to two separate models in JSON format using MongoDB

I recently developed a code with 2 essential functions: module.exports.registerAccount = (reqBody) => { let newAccount = new User({ firstName : reqBody.firstName, lastName : reqBody.lastName, email : reqBody.email, mobileNum : reqBody.m ...

When using window.open in Chrome on a dual screen setup, the browser will bring the new window back to the

When using the API window.open to open a new window with a specified left position in a dual screen setup (screen1 and screen2), Chrome behaves differently than IE and FF. In Chrome, if the invoking screen is on the right monitor, the left position always ...

Is it possible to relocate a function that relies on the success callback of Ajax outside of the callback?

According to JSHint.com: Avoid placing function declarations inside blocks. Opt for a function expression or move the statement to the outer function's top. JSHint advises against keeping this function within the success callback. function matchC ...

The NextJs router encountered an unknown key passed through the urlObject during the push operation

I have a Next.js/React application where I am utilizing the Next Router to include some queries in my URL. However, when using the following function, the Chrome Dev Console displays numerous warnings: const putTargetsToQueryParams = (targets: IFragrance ...

What is the best way to create a navigation bar that opens on the same page when clicked?

Can someone help me figure out how to create a navbar that, when clicked, opens a small window on the same page like in this example image? ...

The React DevTools display components with the message "Currently Loading."

I am currently facing an issue with debugging some props used in my React application. When I try to inspect certain components, they display as "Loading..." instead of showing the normal props list: https://i.sstatic.net/RtTJ9.png Despite this, I can con ...

The CSS for the ajax call functions correctly on desktop devices but is not displaying properly on mobile devices

My ajax call is facing an issue where the CSS classes for a loader and overlay are only being applied in desktop view, not mobile view. I am unsure of what mistake I may be making. Can someone help me resolve this problem? Here is the ajax call: function ...

Steps to display a text box once the dropdown list is updated

I have a dropdown menu with two options <div class="form-group"> <span class="col-sm-4 control-span">Member Type</span> <div class="col-sm-8"> <select class="form-control" id="membertype" name="me ...

eliminate the firebase firestore query using onSnapshot

Seeking assistance with the following code snippet: firebase.firestore() .collection("chatrooms") .doc(`${chatId}`) .collection(`${chatId}`) .orderBy("timestamp") .limit(50).onSnapshot((snapshot) => { //performing oper ...

Problem with javascript querystring code

Currently in the process of writing some vanilla JavaScript code to manipulate query strings without using jQuery. Here's what I have so far: // If there is no viewid in the query string, append it as a new key if (newUrl.indexOf("viewid") == -1) { ...

Discovering the specific style within an inspect-element and transferring it to a JavaScript file

As a novice in the realm of react/javascript, I encountered a situation where I successfully edited a specific style using the inspect element tool. However, despite my efforts, I struggled to locate the corresponding style within the Javascript file. Ha ...

Is there a way to create a JavaScript script that automatically updates a webpage for all users simultaneously?

I have developed a web application that enables users to modify content using JavaScript. Currently, these changes are only visible on the local browser and do not involve AJAX. However, I am wondering how I can ensure that these DOM alterations are refle ...

What is the best way to determine the size of a JSON array that was returned from a server?

I have a JSON array containing objects within an array. I'd like to know how to determine the length of keys and values inside each object. Can anyone assist me in figuring out how to get the length of an object within an array? While I can obtain the ...