Leverage angularjs nested ng-repeats to build intricate table structures

I'm running into some difficulties creating a proper table using nested ng-repeat.

What I'm aiming for is similar to this example: https://jsbin.com/razamagabo/1/edit?output

However, I seem to be stuck at this point: https://plnkr.co/edit/d5voXIpzYL81sSl9BSY2?p=preview

Although I am open to changing my markup from using tables to divs, I am still struggling with the implementation.

<div class="row">
            <div class="col-xs-6" ng-repeat="obj in data">
                {{obj.date}}
                <div ng-repeat="user in obj.users">                 
                    <br>
                    {{user.name}}
                    <br>
                    {{user.mark}}
                </div>
            </div>
        </div>

Answer №1

To effectively showcase your data in the desired format, it may be best to reorganize your data within the JS code before attempting to display it.

Attempting to match user names when they are spread across different objects in the data array can be quite complex.

I recommend handling the processing of your scope.data in the controller (assuming limited control over how the data is received).

After fetching your data...

$scope.data = [
    {
        date:'1-1-2016',
        users:[
            {
                'name':'james',
                'mark':18
            },
            {
                'name':'alice',
                'mark':20
            }
        ]
    },
    {
        date:'2-1-2016',
        users:[
            {
                'name':'james',
                'mark':60
            },
            {
                'name':'alice',
                'mark':55
            }
        ]
    }
]

var userData = {};
var possibleDates = [];
for (dataObj of Object.entries($scope.data)) {
    for (userObj of dataObj) {
        if ( !userData[userObj.name] ) {
            userData[userObj.name] = {};
        }
        userData[userObj.name][dataObj.date] = userObj.mark;
        if (dates.indexOf(dataObj.date) < 0) {
            dates.push(dataObj.date);
        }
    }
}

$scope.users = userData;
$scope.dates = possibleDates;

This will result in an object like this within your scope

$scope.users = {
    'james': {
        '1-1-2016': 18,
        '2-1-2016': 60
    },
    'alice': {
        '1-1-2016': 20,
        '2-1-2016': 55
    }
};

$scope.dates = ['1-1-2016', '2-1-2016'];

This structure appears more suitable for your template. However, it assumes each user has a corresponding entry for every date.

<div>
    <div id='header-row'>
        <div id='empty-corner></div>
        <div class='date-header' ng-repeat='date in $scope.dates></div>
    </div>
    <div class='table-row' ng-repeat='{key, value} in $scope.users'>
        <div class='user-name'>{{ key }}</div>
        <div class='user-data' ng-repeat='date in $scope.dates>
            {{ value[date] }}
        </div>   
    </div>
</div>

If you apply inline-block styles to the rows/elements, this setup should provide the desired outcome.

Alternatively, consider simplifying your data further by consolidating user information into arrays rather than using objects with date keys.

Answer №2

Your current data structure is causing difficulty in displaying the information as desired. You are attempting to iterate over date-users objects within the data array, but then trying to display users from the users array in separate rows. While ng-repeat allows you to loop through rows using tr, it does not allow looping through columns. To achieve your desired layout, you would first need to reorganize your data array to group elements that should be visible in the same row into a single object in the array. Currently, these elements are stored in two separate objects: James mark: 18 and James mark: 60.

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 art of filtering data using jQuery's data-filter feature

I'm struggling to create a jQuery filter function that will display only the items belonging to a specific category when that category is clicked on. Although I have written some functions, I can't seem to get it to work properly. My goal is to ...

The Ionic project compilation was unsuccessful

Issue: This module is defined using 'export =', and can only be utilized with a default import if the 'allowSyntheticDefaultImports' flag is enabled. Error found in the file: 1 import FormData from "form-data"; ~~~~~~~~ node ...

Using Regular Expressions as an Alternative to Conditionals

My knowledge of RegEx is limited, but I'm trying to make the following expression work with Javascript/Typescript: /^({)?(?(1)|(\()?)[0-9A-F]{8}(-)?([0-9A-F]{4}(?(3)-)){3}[0-9A-F]{12}(?(1)}|(?(2)\)))$/i This RegEx is used to check if a str ...

Different kinds of garbage collection operations in NodeJS

When utilizing the perf_hooks module in NodeJS, we have access to information regarding garbage collection. This can be achieved by using PerformanceObserver, which is triggered with each garbage collect event. const obs = new perf_hooks.Performanc ...

Troubleshooting challenges with updating Ajax (SQL and add-ons)

I am currently facing some specific issues with an ajax update feature, but I am confident that it just requires some fine-tuning to work perfectly. Below, I will outline the problems clearly: In my setup, there are two files that interact with each othe ...

I have noticed that the Javascript code is being loaded prior to the completion of my HTML/CSS page for some unknown

I am completely new to the world of web development. I'm encountering an issue where my JavaScript code (specifically alerts) is loading before my HTML/CSS page has fully loaded. I've been using sample alerts to test this out, and ideally, they s ...

Exploring Angular 1.x, utilizing both ES5 and ES6, and incorporating Karma for comprehensive testing

I am currently developing tests for an angular app that consists of a mix of ES5 and ES6 files. To transpile the ES6 files, I am using babel CLI with the options --modules system --module-ids. Here is an example of what I have: ES5 file: angular.module(& ...

Creating a file solely for route definitions and then employing them within index.js

My index.js file contains the following routes: import { createRouter, createWebHistory } from '@ionic/vue-router'; import { RouteRecordRaw } from 'vue-router'; const routes = [{ path: '', redirect ...

The dispatch function in redux-thunk is not functioning as expected

Having trouble with thunk and async dispatching? Check out this code snippet: function fetchProvider() { return (dispatch) => { graphqlService(fetchProviderQuery) .then((result) => { dispatch({ type: FETCH_PROVIDER, ...

toggle classes using jQuery when a link is clicked

I'm currently working on a jQuery function that will apply a class to a selected link (which opens a page in an iframe) and then remove that class when another link is chosen. Previously, I received assistance from another member for a similar task in ...

There are no documents found with the specified UUID in MongoDB

I have been attempting to retrieve a specific document from MongoDB that includes the field "ownerId" containing a binary UUID. In the Mongo console, when I run the command db.dataset.find({ownerId: BinData(3,"ZQ6EAOKbQdSnFkRmVUUAAA==")}).pretty() The ou ...

Tips for enhancing the efficiency of large-scale data Angular Material apps when using internet explorer

Our team is currently working on an Angular Material application that deals with a significant amount of data, ranging from 20 to 40 thousand rows. While this application performs smoothly in Chrome, we are experiencing slow performance issues in MSIE 11 ...

Ways to verify that a javascript function generates an object and executes a method within that object

Currently, I am in the process of updating server code written in nodejs and incorporating unit tests into the mix. However, I have encountered a challenge that I need assistance with: classX.prototype.methodX = function () { // Create new session ...

Repeated firing of jQuery's Ajaxstop within a click event

When using the quantity plus button on the woocommerce cart page and reaching maximum stock, I want to display a notice. However, due to an auto update on the cart, I have to wait for the ajax load to complete before showing the notice. My script revealed ...

Organizing NodeJS modules in a way that mirrors Maven's groupId concept

I am making the switch to NodeJS after working extensively with Maven. In Maven, we are familiar with the groupId and artifactID, as well as the package name when starting a new project. However, in NodeJS, I only see a module name. The concept of groupI ...

Tips for altering the appearance of a button when moving to a related page

I have a master page with four buttons that have a mouse hover CSS property. Each button's corresponding response page is defined on the same master page. Now, I want to change the button style when the user is on the corresponding page. How can this ...

Setting the initial values of state variables upon rendering of a component and using custom hooks

I have a file called Body.jsx that handles fetching data from an API and filtering it. In an attempt to clean up the code, I created a custom hook named useResData specifically for fetching data: export const Body = () => { const resDataList = useResD ...

Generating a personalized array by matching an array with an object using JavaScript / Node.js

let obj ={ 97:{ data:"OS", location:"system", access:"globally", parameters:"aed31" }, 490:{ data:"Ae-ds", location:"rootpath", access:"admin rights", parameters:"4fsje" }, 278:{ data:"config", location:"system", ...

What is the best way to remove an element using Python selenium?

I'm facing a challenge trying to remove an element for the past hour, but I haven't been successful so far. The element can only be accessed using its class name. I've attempted the following: js = "var aa=document.getElementsByClassName(&a ...

Is it possible for Javascript to handle a string of 27601 characters in length?

I have created a webmethod that returns an object containing strings. Each string in the object is of length 27601. This pattern continues for all array members - str(0) to str(n). When my webmethod returns this exact object, I encounter an issue on the c ...