Table created using ng-repeat to display a nested array

Take a look at this straightforward json data:

$scope.fruits = [
{
    "type": "fruit",
    "content": [
        {
            "name": "banana",
            "type": "edible"
        }
        {
            "name": "apple"
            "type": "edible"
        }
    ],
    "id": 1
},
{
    "type": "vegetable",
    "content": [
        {
            "name": "eggplant",
            "type": "edible"
        },
        {
            "name": "poison ivy",
            "type": "inedible"
        }
    ],
    "id": 2
}
]

I envision my table to be structured in the following way:

<tr>
    <td> fruit </td>
    <td> 1 </td>
    <td> banana </td>
    <td> edible </td>
</tr>
<tr>
    <td> fruit </td>
    <td> 1 </td>
    <td> apple </td>
    <td> edible </td>
</tr>
<tr>
    <td> vegetable </td>
    <td> 2 </td>
    <td> eggplant </td>
    <td> edible </td>
</tr>
<tr>
    <td> vegetable </td>
    <td> 2 </td>
    <td> poison ivy </td>
    <td> inedible </td>
</tr>

The challenge is that nesting loops using ng-repeat doesn't seem to work as intended. Here's an unsuccessful attempt:

<tr ng-repeat = "item in fruit in fruits">
    <td> {{fruit.type}} </td>
    <td> {{fruit.id}} </td>
    <td> {{item.name}} </td>
    <td> {{item.type}} </td>
</tr>

Would it be better to flatten my json structure or is there a workaround with AngularJS to handle this? I've experimented with filters but haven't had success. Any guidance on achieving the desired outcome would be greatly appreciated.

Answer №1

<div ng-show="showFruits">
    <ul>
        <li ng-repeat="fruit in fruits">
            {{fruit.name}} - Type: {{fruit.type}}
        </li>
    </ul>
</div>

Alternatively, you may need to create a new data structure based on the current one.

Answer №2

To avoid nesting ng-repeats, one alternative is to restructure the object, for example:

var allItemsUpdated = [];
items.forEach(function(item) {
  item.details.forEach(function(d) {
    allItemsUpdated.push({
      category: item.category,
      id: item.id,
      name: d.name,
      type: d.type 
    });
  });
});

Then you can iterate through them in Angular using something like this:

<tr ng-repeat = "item in allItemsUpdated">
    <td> {{item.category}} </td>
    <td> {{item.id}} </td>
    <td> {{item.name}} </td>
    <td> {{item.type}} </td>
</tr>

Answer №3

Give this method a try. Hopefully, it will meet your expectations.

<table border="1">
    <tbody ng-repeat="item in veggies">
        <tr ng-repeat="veggieUnit in item.content">
            <td>{{item.category}}</td>
            <td>{{item.code}}</td>
            <td>{{veggieUnit.name}}</td>
            <td>{{veggieUnit.type}}</td>
        </tr>
    </tbody>
  </table>

Answer №4

HTML Tag

<custom-grid items="items"></custom-grid>

Grid Directive

app.directive('customGrid', function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            var html = '<grid>';
            angular.forEach(scope[attrs.items], function (item) {
                angular.forEach(item.contents, function (content) {
                  html += '<row><cell>' + item.id + '</cell>';
                  html += '<cell>' + item.type + '</cell>';
                  html += '<cell>' + content.name + '</cell>';
                  html += '<cell>' + content.type + '</cell></row>';
                });
            });
            html += '</table>';
            element.replaceWith(html)
        }
    }
});

--JS

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

When I press the button, the text box fails to refresh

Here is an example I want to share with you: code demonstration. Below is the HTML code snippet: <input id="uploadFile" placeholder="Choose File" disabled="disabled" /> <div class="file-upload btn btn-primary"> <span>Upload</span ...

Lifting Formik's "dirty" value/state to the parent component: A step-by-step guide

Parent Component const Mother = () => { const [dusty, setDusty] = useState(false) return ( <ChildComponent setDusty={setDusty} /> ) } Child.js ... <Formik initialValues={initialValues} onSubmit={onSubmitHandler} validationSchema={sch ...

Guide to using AJAX to send a select tag value to a PHP script on the current page

Issue I am facing a problem where I need to utilize the select tag in order to choose a value and then send that value via an ajax call to a PHP script embedded within the same page. In my code, I have implemented the select tag and upon selecting a valu ...

Posting an HTTP request in Sails JS with the content-type set to application/json

Can someone please help me with writing a sails-js controller to handle the following HTTP request? I am trying to send raw data with Content-Type: application/json. I know how to work with POST requests using form-data, where the req.body in the control ...

How should we properly insert a line break here? Additionally, can you explain why the square is displaying the incorrect color?

Here is the code snippet that I am currently working on. <html> <head> <script> onload=function main() { function createSquare(type) { let square = document.createElemen ...

Cannot trigger a click event on nginclude in AngularJS

I have a question regarding including a new page using the nginclude directive. The click event defined in the included page is not working properly. Main Application: <div ng-app=""> <input type="text" ng-model="ss"/> <div ...

Utilizing AngularJS for Converting Date Formats from JSON and HTML Elements

So I have this controller set up. function TestCtrl($scope) { var contentFromJson = 'Hi! this is <b>Bold</b> and <i>Italic</i>'; var dateFromJson = '/Date(1394526738123)/'; $scope.Date = dateFromJso ...

What is the proper method for invoking object (class) methods from a router?

My apologies for the vague title. Let me clarify what I am attempting to accomplish. In this scenario, there are two main components: A class called 'wallet.js' A router named 'index.js' which handles GET requests This is my objectiv ...

Encountered a problem while trying to deserialize JSON using DataContractJsonSerializer

I'm facing a challenging dilemma. Currently, I am attempting to deserialize the JSON string retrieved from an ASP.NET Web Service: "{\"d\":{\"__type\":\"KPCServer.LogonResult\",\"User\":{\"UserId\":&b ...

AngularJS - seamless navigation to url with hash symbol

Currently, I am in the process of developing a web application using a combination of AngularJS and Laravel. Everything seems to be working fine when I navigate through the URLs and links within the app. However, an issue arises when I try to directly inp ...

Include scrollView on smaller screens based on conditions

While incorporating an overlay in my application, how can I integrate a ScrollView specifically for smaller devices? Initially, I am checking the width: const windowWidth = Dimensions.get("window").width; Subsequently, I am attempting to display the Scro ...

Struggling to showcase information from a JSON file within an embed on a webpage

I am struggling to display the data from my JSON file in an embed. I need assistance with finding a solution for this issue. Here is the content of the JSON file: { "Slims Mod Bot": { "Felix\u2122": 2, "Dus ...

Remove the last column from the UI grid and add a Bootstrap dropdown menu inside each cell

In order to retrieve the data from the ui-grid, I implemented the following method: $scope.getData = function() { var a = $scope.gridOpts.data; alert(JSON.stringify(a)); } However, I noticed that it displays an extra column which I want to remove ...

A guide to selecting the bookmark with a URL that is on a currently opened page

To gain a clearer understanding of my goal, follow these steps: Open the Chrome Browser and go to a URL, such as https://www.google.com. Once the page loads, locate and click on the bookmark labeled "ABC", which contains the URL ({window.open('/ ...

When I attempt to send a PUT request, the req.body object appears to be empty. This issue is occurring even though I have implemented the method override middleware

I am currently facing an issue with updating a form using the put method. To ensure that my form utilizes a PUT request instead of a POST, I have implemented the method override middleware. However, upon checking the req.body through console log, it appear ...

Passing a function to a dynamically created child in React with an extra parameter

In my React project, I am looking to dynamically generate child components and have them trigger an onClick event from their parent or grandparent component. What I aim to achieve is the following flow: When rendering the parent component Pass a referenc ...

Guide on connecting a JSON-generated list to showcase the data from another JSON document

I am currently working on a project that involves calling a JSON file named sections.json. From this file, I am accessing the array called sections, looping through each item, and adding the value of name to a list item (li). My goal is to create a link or ...

Searching for multiple items in Postgres Json can be achieved by utilizing the JSONB data

In my Postgres DB, I store data in a json column called items which keeps all the information in a single row. [ { "item_code":"UMI MAIZE Box (10.0 PC)", "name":"5e0648a9e5", "uom":null ...

When Vue.js is combined with axios, the data may not be properly updated

As I navigate through the world of Vue.js, I encounter a rather peculiar issue that has left me scratching my head ( at least in my humble opinion ). Let's take a look at the code snippet: import Vue from 'vue/dist/vue.js'; import axios fr ...

Create names for links using jQuery based on the data received from an AJAX response

I am currently utilizing the jQuery UI tooltip script available at this link. As a result, I have tooltip links with varying "data-id" attributes like so: <a tooltip-link data-id="12555"></a> <a tooltip-link data-id="38"& ...