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.

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

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

Support for h264 in Windows Media Player across various versions of Windows operating system

Are there specific versions of Windows that are capable of playing h264 videos with Windows Media Player installed by default? Is it feasible to determine this support using Javascript? We currently deliver MPEG-4 video files through Flash, but some users ...

Creating a custom route in Node.js using Express for posting content and adding it to a specific user's page

I am currently working on a node.js express project where I am developing a health app for a trainer to manage his clients. The main functionality of the app includes allowing the trainer to access individual client profiles and view their exercise list by ...

Utilizing JavaScript to retrieve input names from arrays

This is the HTML form that I am currently working with: <form action="#" method="post"> <table> <tr> <td><label>Product:<label> <input type="text" /></td> <td><label>Price:<label> ...

Data binding in Vue.js seems to be malfunctioning

I'm having trouble with my Vue component creation. I've been using v-show to hide certain elements, but it doesn't seem to be working as intended. The goal is to hide an element when clicked from a list by setting element.visible to false i ...

Utilizing Think ORM seamlessly across multiple files without the need to repeatedly establish a connection to the

I'm facing a situation where I have numerous models for thinky, and in each file I am required to create a new object for thinky and connect it multiple times due to the high number of models. var dbconfig = require('../config/config.js')[& ...

The error message states that the provided callback is not a valid function -

I seem to be encountering an issue with the code snippet below, which is part of a wrapper for the Pipl api: The main function here performs a get request and then retrieves information from the API Any assistance in resolving this error would be greatly ...

The issue of overwritten callbacks is occurring due to the use of multiple .use() functions on the

Utilizing a module known as consign, I am able to conveniently include multiple modules from a directory all at once, eliminating the need for numerous require statements. In my code, I have set the mount path for each endpoint at the beginning of the rout ...

Fixing My Code with JQuery Tabs and Hyperlinking

I have come across a problem while using multiple pages with jQuery tabs. Let's consider Page1.html with #tab1 and #tab2, and Page2.html with #tab3 and #tab4. Here are the issues I am facing: 1) Within the tab content of Page1.html#tab2, there is a h ...

Localization for Timeago JS Plugin

Currently, I have integrated the jQuery TimeAgo plugin into my project and included the following code snippet for localization in Portuguese: // Portuguese jQuery.timeago.settings.strings = { suffixAgo: "atrás", suffixFromNow: "a partir de agora", ...

Implementing jQuery UI toggleClass method to seamlessly alternate between two distinct CSS classes

My goal is to toggle between two CSS classes on a selector click using Jquery UI .toggleClass(), but unfortunately, it's not producing the desired toggle effect. $(".toggle").click(function () { $(".archivePosts .columns").removeClass( "l ...

How can I retrieve objects using the JSON function?

I need to design a function that returns objects like the following: function customFunction(){ new somewhere.api({ var fullAddress = ''; (process address using API) (return JSON data) })open(); } <input type= ...

Transfer the information on the onClick event to the loop's function

When creating my component within the parent component, I follow this approach: renderRow(row){ var Buttons = new Array(this.props.w) for (var i = 0; i < this.props.w; i++) { var thisButton=<FieldButton handler={this.actionFunction} key={&ap ...

The JSON response is being overridden by a catch-all URL and ends up being displayed as a 404 error page

I'm dealing with a React/Express setup that looks something like this (simplified for clarity): const path = require('path') const express = require('express') const CLIENT_BUILD_PATH = path.join(__dirname, '../build') ...

Calculating the average of object attributes within a Python list

Seeking solution in Python. I have a list (A) containing numpy object arrays (B), and I wish to calculate the mean of one specific variable within each object in the B array. Currently, my approach involves iterating through the B array, performing summat ...

I am experiencing difficulties with displaying my array of JSX elements in the render function of my ReactJS application. What could be

I am currently working on a trivia application and encountering an issue with inserting an updated array of "Choice" elements for each question. Despite my efforts, whenever I attempt to insert an array of JSX elements, the array appears blank. This is qui ...

Persistent hover effect for collapsible accordion panels when closing them

My simple accordion features a functionality where a class of .open is added to the title + content group when you open a panel for styling purposes. Everything works smoothly, but I've noticed on my phone that after clicking to close a panel, the hov ...

Is it necessary for NPM to execute scripts labeled as dependencies during the npm i command execution?

When npm i is run, should it execute the scripts named dependencies? I've observed this behavior in the latest version of Node (v19.8.1) and I'm curious if it's a bug. To replicate this, follow these steps: mkdir test cd test npm init -y T ...

When trying to implement appDir and withPWA in next.config.js, an error has been encountered

My next.config.js is set up with next-pwa and an experimental app feature included. const withPWA = require('next-pwa'); module.exports = withPWA({ pwa: { dest: 'public', disable: process.env.NODE_ENV === 'development&ap ...

Is NG-True-Value exclusively for string literals?

I am attempting to utilize the ng-true-value directive with expressions or objects: I experimented with these options: ng-true-value={{selection}} ng-true-value="selection" ng-true-value="{{selection}}" Unfortunately, none of these approaches h ...

Angular dynamic calculations for min and max values result in an unusual user interface

I am encountering an issue with a datetime-local input field that has max and min attributes. <input type="datetime-local" ng-model="model.date" min="{{min}}" max="{{max}}"> These attributes are dynamically set based on the date from another input ...