How can you create an intricate HTML table using AngularJS with data nested on various levels?

Creating a table from data with multiple levels of arrays and sub-arrays can be challenging, especially when existing solutions are limited to two levels. For instance, consider the sample data below:

$scope.professors = [{
    'name': 'Albert Einstein',
    'classes': [{
        'name': 'Physics 101',
        'students': [{
            'name': 'Joe',
            'grade': 'B'
        }, {
            'name': 'Mary',
            'grade': 'A'
        }]
    }, {
        'name': 'Physics 201',
        'students': [{
            'name': 'Gunther',
            'grade': 'C'
        }, {
            'name': 'Hans',
            'grade': 'C'
        }]
    }]
}, {
    'name': 'Charles Darwin',
    'classes': [{
        'name': 'Biololgy 101',
        'students': [{
            'name': 'Danielle',
            'grade': 'A'
        }, {
            'name': 'Anne',
            'grade': 'A'
        }]
    }, {
        'name': 'Biology 201',
        'students': [{
            'name': 'Frida',
            'grade': 'A'
        }, {
            'name': 'Fritz',
            'grade': 'F'
        }]
    }]
}];

To display all professors along with their disciplines, students, and grades in a table-report, you'd typically use an HTML table structure like this:

<table>
    <tbody>
        <!-- Table content goes here -->
    </tbody>
</table>

The existing solutions often rely on ng-repeat for each professor and another within that for each "class" for that professor. However, extending this to include students poses a challenge.

Answer №1

After struggling for a while and racking my brains, I finally discovered a solution using ng-repeat-start

<table>
    <tbody>
        <tr ng-repeat-start="p in professors" ng-if="false"></tr>
        <tr ng-repeat-start="c in p.classes" ng-if="false"></tr>
        <tr ng-repeat="s in c.students">
            <th ng-if="$parent.$first && $first" rowspan="{{p.count}}">
                {{p.name}}
            </th>
            <th ng-if="$first" rowspan="{{c.students.length}}">>{{c.name}}</th>
            <td>{{s.name}}</td>
            <td>{{s.grade}}</td>
        </tr>
        <tr ng-repeat-end ng-if="false">></tr> <!-- classes -->
        <tr ng-repeat-end ng-if="false">></tr> <!-- professors -->
    </tbody>
</table>

This method effectively creates valid HTML table structure. By utilizing ng-if="false" on the ng-repeat-* elements, they are able to iterate over the arrays without actually displaying any elements on the page. The only rows generated are the ones within s in c.students.

An additional step I had to take was introducing a new property inside each professor object called count, which stores the total number of students enrolled in all classes. This was necessary for the rowspan and can easily be calculated when retrieving data from the server.

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 Ionic/AngularJS button can only be clicked from the bottom, and the model is not appearing as

As a newcomer to the world of Angular, Ionic, and programming in general, I decided to venture into developing a small phone app. However, along the way, I encountered two puzzling problems. Here is the codepen link where you can find my code: http://codep ...

Alert the host about any updates

I am currently working on an ASP.NET application that is hosted by a C# application using WebBrowser. The ASP.NET application runs within the C# application environment. My challenge lies in finding a way to notify the C# application when certain events, ...

Unable to eliminate the border from the input field

Currently utilizing Chrome browser and implementing Materialize CSS within an Angular application. Struggling to eliminate the persistent blue border that appears around my number input when focused. Have experimented with various combinations of code adju ...

Using the `forEach` method nested within another `forEach

I'm facing an issue with the useEffect hook where it seems to not be rendering correctly. My cardArticle is only concatenating the last array and that's it. Below is the code snippet: const [articles, setArticles] = useState([]); const [cardA ...

retrieving the configuration settings from my customized service

When attempting to access my custom service within its config property in order to inject an HTTP interceptor, I am encountering the following issue: angular .module("common.services") .factory("redirectService", [" ...

Implementing a scrolling feature in the autocomplete textbox to handle lengthy data

I successfully implemented an autocomplete multiselect textbox functionality that is working well. However, I am facing an issue with a long list of values appearing when I have 3000 records and type A in the textbox. Please refer to the screenshot below: ...

How to execute database update queries in NodeJS?

I'm encountering an issue with a piece of code where only the first value in the database is being updated, rather than all rows. I'm looking to update multiple rows using a loop. How can I achieve this by selecting a column value from a table an ...

Safari not accepting HTTPS requests with Authorization headers

Scenario Encountering issues with XHR requests utilizing Authorization headers over HTTPS in Safari (IOS and MacOS). The requests fail to reach the server, while IE, Chrome, and Firefox work fine. A valid Letsencrypt certificate is being used without any ...

What causes the picturesArray to remain consistently void?

const fetch = require("node-fetch"); let images = []; fetch('http://www.vorohome.com//images/assets/159314_887955.png') .then(response => response.buffer()) .then(buffer => { const data = "data:" + response.headers.get ...

Issues with Firefox and FCKeditor displaying cftextarea on a single device

On a single computer in our network, the cftextarea is not rendering properly in Firefox 41.0.2. The Firebug console displays errors only on that specific computer; SyntaxError: missing } after function body fckeditorcode_gecko.js:108:329 ReferenceError: ...

Issue with Cloud Code function preventing data from being saved

After successfully testing this code in Angular and getting the correct responses in console.log, I decided to migrate it to cloud code. Since the function manipulates data in the user table, I had to use the master key and implement it in cloud code. Howe ...

Tips for configuring Visual Studio Code to utilize path mappings for handling automatic imports

In order to streamline my project and avoid messy paths, I am implementing absolute paths that will allow for consistent imports regardless of the file's location in the project tree. For this purpose, I made adjustments to the tsconfig.json: "paths ...

Tips on changing an image with a button click

I am currently working on a project where I have a div tag containing an image that is selected randomly from different arrays based on topics. However, I am facing some challenges in making the image change when the "go" button is clicked. I want the if ...

Is the DOMContentLoaded event connected to the creation of the DOM tree or the rendering tree?

After profiling my app, I noticed that the event is triggered after 1.5 seconds, but the first pixels appear on the screen much later. It seems like the event may only relate to DOM tree construction. However, this tutorial has left me feeling slightly con ...

Could someone assist me with understanding how to use the Load function in JQuery?

I have a set of links with the class "ajax" that are meant to fetch content from an element with the id "test" in the file "data.html" located in the same directory. This content should then be inserted into the div with the id "content" on my page: <s ...

Implementing a function on every object of a class

As part of my practice, I am developing a form validation program using classes to store data related to each field. When the user submits the form, any invalid fields are supposed to be highlighted for correction. The conventional approach would involve a ...

When visiting this website, a special feature is enabled where the page will automatically refresh every 5 seconds. As the countdown begins, the numbers 5, 4,

Could use some assistance with setting up an HTML page to reload every 5 seconds and display a countdown when the refresh link is clicked. After clicking the refresh link, it should disappear and show a countdown from 5 to 1 before reloading the page aga ...

Create a function that can accept either no parameters or one parameter depending on the input parameter provided

Do you think there is a more efficient way to write this code? The function Z can be called with either one parameter or with no parameters. If the parameter Y is passed in, then the function z(y) is returned, otherwise just run the function z() async x ...

AJAX parsing through JSON files generated by PHP

Need help with sending a json to an ajax call and reading it when it's sent. Plus, the json structure seems off due to the backslashes... This is the ajax function in question: function find(){ var type = $('#object_type').val( ...

Having trouble resolving this technical problem in Express.js and JavaScript programming

try { console.log('11111') const { data: { tasks }, } = await axios.get('/api/v1/tasks') console.log('22222 ' + await axios.get('/api/v1/tasks') ) console.log('33333 ' + tasks) https://i.sstatic.net/mLLV ...