Can someone please explain how to create a nested table within a single column in Angular JS when it contains a list of values?

index.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.data =[{"Id":1,"Title":"en-US","Description":"UnitedStates","MyValues":[{"Id":100,"Value":"Save"}]},
{"Id":1,"Title":"en-UK","Description":"UK","MyValues":[{"Id":102,"Value":"Delete"}]}]
  $scope.cols = Object.keys($scope.data[0]);

  $scope.notSorted = function(obj){
    if (!obj) {
        return [];
    }
    return Object.keys(obj);
}
});

index.html

<table border=1>
      <thead>
        <tr>
          <th ng-repeat="key in notSorted(cols)" ng-init="value=cols[key]">{{value}}</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="row in data">
          <td ng-if="!$last" ng-repeat="dat in notSorted(row)" ng-init="value=row[dat]">{{value}}</td>
        </tr>
      </tbody>
    </table>

The table generated is perfect, but there is an issue with the column MyValues. I have a list of data and would like to create a nested table with all list values.

How can this be achieved? I want to identify if any column contains a list and if so, then generate a nested table. You can check out this plunker http://plnkr.co/edit/Ixvp8B0dRwOBDHflmu2j?p=preview

Answer №1

Here is an example of how you can structure your markup:

<table>
  <thead>
    <tr>
      <th ng-repeat="(k,v) in data[0]">{{k}}</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="item in data">
      <td ng-repeat="(prop, value) in item" ng-init="isArr = isArray(value)">
        <table ng-if="isArr">
          <thead>
            <tr>
              <th ng-repeat="(sh, sv) in value[0]">{{sh}}</th>
            </tr> 
          </thead>
          <tbody>
            <tr ng-repeat="sub in value">
              <td ng-repeat="(sk, sv) in sub">{{sv}}</td>
            </tr>
          </tbody>
        </table>
        <span ng-if="!isArr">{{value}}</span>
      </td>
    </tr>
  </tbody>
</table>

To view the full code, visit: https://gist.github.com/anonymous/487956892d760c17487c

Answer №2

I'm not entirely certain about the outcome you are aiming for, but here are some suggestions that might inspire you.

Check out: http://example.com/edit/abcd1234

script.js

let app = angular.module('exampleApp', []);

app.controller('MainController', function($scope) {
  $scope.name = 'World';
  $scope.data = [
    {"Id":1,"Title":"en-US","Description":"UnitedStates","MyValues":[{"Id":100,"Value":"Save"}]},
    {"Id":1,"Title":"en-UK","Description":"UK","MyValues":[{"Id":102,"Value":"Delete"}]}
  ];
  $scope.cols = Object.keys($scope.data[0]);

  $scope.notOrdered = function(obj){
    if (!obj) {
      return [];
    }
    return Object.keys(obj);
  }  
});

page.html

<table border=1>
  <thead>
    <tr>
      <th ng-repeat="key in notOrdered(cols)" ng-init="value=cols[key]">{{value}}</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in data">
      <td ng-if="!$last" ng-repeat="dat in notOrdered(row)" ng-init="value=row[dat]">
        <div ng-if="value[0].Id">
          <table>
            <tr>
              <td>Id:</td><td>{{value[0].Id}}</td>
            </tr>
            <tr>
              <td>Value:</td><td>{{value[0].Value}}</td>
            </tr>
          </table>
        </div>
        <div ng-if="!(value[0].Id)">
          {{value}}
        </div>
      </td>
    </tr>
  </tbody>
</table>   

If you want to make it more flexible, consider using something like

<div ng-if="angular.isArray(value)">
instead of <div ng-if="value[0].Id">. I didn't have time to test this approach, but it's worth exploring further.

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

Having trouble aligning input fields and buttons using Angular

I am encountering an issue with aligning an input and button on the same line. As a newcomer to using Angular-Material, I have been unable to find any resources or forums that address my specific problem. One workaround I found was placing the md-button o ...

Is it possible to view the frames/packets being transmitted from an EJS or HTML form to the Express backend using Express Js?

My current computer science assignment involves visually representing the data transfer process between a frontend and backend. I don't need to show the full data, just the flow of chunks and how it navigates through protocols. Could someone please g ...

Eliminating characteristics and rejuvenating the component

I have divs on my webpage that I want to keep hidden until a specific element is clicked. When trying to hide them, I encountered three options: visibilty: hidden - I didn't like this because the hidden div still took up space in the layout. displa ...

Preventing a web component from loading in Angular until its template is fully populated

Incorporating a web component into my Angular application has proven to be tricky. I am utilizing Angular attribute bindings to populate the component dynamically: https://angular.io/guide/attribute-binding Interestingly, setting hardcoded values for the ...

Displaying the information of one formgroup inside another formarray

Utilizing the angular reactive forms module to connect to various formgroups within a formarray named "days." This information is displayed in a material drag and drop loop in the template. Upon clicking a button on the loop divs, details about the specifi ...

Incorporate content upon button click using Javascript

Looking to create a unique Survey layout that includes: Question Name Options The question name is editable and can be changed with a click. Initially, there is one option with a checkbox to select it. This option should also update when clicked. Addit ...

AngularJS: Service variable not triggering $watch when updated within a directive's call

When I modify the service variable using a controller function, the $watch is triggered. However, it does not trigger when the same variable is changed by a directive. <html> <head> <meta charset="UTF-8"> <script src = "https:/ ...

What steps can be taken to verify values using the console bind function?

Is there a way for developers to check various things in the console while typing code and pressing enter? I attempted to do it but couldn't achieve the desired results. Initially, I added a button on fiddle <button id="test">test< ...

Error in TypeScript when using Google Maps React with Next.js: there is a possibility that infoWindow.close is undefined

Working on a small project in next.js (typescript) utilizing the google maps api with a KmlLayer. I want my map to interact with another component, SensorInfo. The current setup allows for smooth interaction between them - when SensorInfo is closed, the in ...

What is the correct way to invoke a function contained within an object that is stored in an array?

I've encountered a problem with my program. I'm attempting to invoke a function that is part of an object stored in an array, but I'm having difficulty calling the function correctly. //Initialize Array for Storing Projects let allProjects ...

What causes a delay of one iteration in the $location.search method when used within the _.debounce() function in lodash?

In the code snippet below, I encountered an unexpected behavior: $scope.$watch('filters', _.debounce(function(newValue, oldValue) { $location.search({test : newValue}).replace(); }, 500), true); What's happening is that the URL only ...

AWS Lambda encountered an issue: Task terminated unexpectedly prior to finishing the operation

I've scoured various Stack Overflow threads for solutions to my issue, but no luck so far. As a beginner in this field, I might not be implementing the suggested fixes correctly. Here's my code, and any help would be greatly appreciated. var mys ...

Tips for incorporating AJAX loaded content with an AngularJS expression using jQuery

I'm having some trouble with this issue and I could really use some help finding the solution. Check out the fiddle here. Clarification 1) I am receiving template HTML via an AJAX request, and everything seems to be working fine. Here is a snippet ...

Express app issues error: JSON response not returned properly - Uncaught SyntaxError: Unexpected end of data

I'm in need of some fresh perspective. My goal is to have a basic Express app return JSON data (in this case, a Firebase token) every time a request is made to it. Here's the code for my Express server: app.get('/validate', function ...

Choose a particular JSON dataset when clicking on it

I am working with a JSON object that looks like this: var facilityDetails = [ { "level": 1, "LocationId": 1, "LocationName": "This is an example of a multi-line ellipsis.This is an example of a multi-line ellipsisThis is an example of ...

Exploring Typescript's ability to recursively deduce object attributes

Imagine having this AnalyticsService class export class AnalyticsService { static sendAnalytics(eventName: string) { console.log(eventName); // logic here... } static EVENTS = { Header: { LogoClicked: "Header: Logo Clicked&quo ...

Loading JS and CSS files in relation to the website root directory

When it comes to including CSS/JS files, what are the best practices for defining the file URI? Some people prefer to include files relative to the website root by specifying the full URI: <link rel="stylesheet" href="/my/path/to/css/main.css"> Thi ...

Customize the text that appears when there are no options available in an Autocomplete component using React

Recently, I came across this Autocomplete example from MaterialUI that caught my attention. https://codesandbox.io/s/81qc1 One thing that got me thinking was how to show a "No options found" message when there are no search results. ...

Switching Classes with a Click of a Button

Hey there, I'm currently using this menu: spoilers.tumblr.com/tvschedule, and I have a script below. The functionality works well with the click event, but I'm having some trouble with the hovering effect. To make certain classes visible on hover ...

Sending a POST request to a PHP file in React: A Step-by-Step Guide

Just starting out with reactjs and trying to figure out how to send an ajax request to a server (php file). Here's the structure of my project: check it out here src/index.js import React from 'react'; import ReactDOM from 'react-dom& ...