Create a table using Angular and Jade that iterates through nested JSON data using ng-repeat

Here is a snippet of my JSON data:

   {
  "contact-info": {
    "phonebook": [
      {
        "name": "John Snow",
        "phones": [
          {
            "phone": "home",
            "number": "1234"
          }
        ],
        "nick": "bastard"
      },
      {
        "name": "Arya Stark",
        "phones": [
          {
            "phone": "cell",
            "number": "234"
          },
          {
            "phone": "work",
            "number": "345"
          },
          {
            "phone": "home",
            "number": "456"
          }
        ],
        "nick": "no one"
      },
      {
        "name": "Theon",
        "phones": [
          {
            "phone": "fax",
            "number": "567"
          }
        ],
        "nick": "Reek"
      },
      {
        "name": "Aemon",
        "phones": [
          {}
        ],
        "nick": "maester"
      }
    ]
  }
}

I am attempting to use Angular to create a table that resembles this design: https://i.sstatic.net/e0w9q.png

Currently, I am able to display only the first phone number for each person using Angular:

tbody
    tr( ng-repeat="person in JSON.contact-info.phonebook")
        td {{person.name}}
        td {{person.phones[0].phone}}
        td {{person.phones[0].number}}
        td {{person.nick}}

However, I am facing challenges when trying to loop through the nested 'phone' section. How can I achieve this?

Thank you

Answer №1

give this a shot.

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

app.controller("ctrl" , function($scope){
  $scope.contacts = {
    "phonebook": [
      {
        "name": "John Snow",
        "phones": [
          {
            "phone": "home",
            "number": "1234"
          }
        ],
        "nickname": "bastard"
      },
      {
        "name": "Arya Stark",
        "phones": [
          {
            "phone": "cell",
            "number": "234"
          },
          {
            "phone": "work",
            "number": "345"
          },
          {
            "phone": "home",
            "number": "456"
          }
        ],
        "nickname": "no one"
      },
      {
        "name": "Theon",
        "phones": [
          {
            "phone": "fax",
            "number": "567"
          }
        ],
        "nickname": "Reek"
      },
      {
        "name": "Aemon",
        "phones": [
          {}
        ],
        "nickname": "maester"
      }
    ]
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl" class="panel-group" id="accordion">
  
  <table>
    <thead>
    <tr>
      <td>name</td>
      <td>phone</td>
      <td>number</td>
      <td>nickname</td>
      </tr>
    </thead>
     <tbody  ng-repeat="(key,value) in contacts">
       
    <tr ng-repeat="person in value.phonebook">
       <td >{{person.name}}</td>
       <td ng-repeat="phone in person.phones">{{phone.phone}}{{phone.number}}</td>
       <td >{{person.nickname}}</td>
    </tr>
       
       </tbody>
    </table>
            
</div>

Answer №2

If you're looking to display data using ng-repeat, you will need to use nested repeats. One for looping through people and another for their respective phones.

The challenge lies in iterating twice while still generating table rows. Two techniques that can assist you are the ng-repeat-start and ng-repeat-end directives, as well as the ability to include directives within comments.

 tbody
   // ng-repeat-start='person in JSON.JSON.contact-info.phonebook'
   tr(ng-repeat='phone in person.phone')
     td {{ person.name }}
     td {{ phone.phone }}
     td {{ phone.number }}
     td {{ person.nick }}
   // ng-repeat-end

This code snippet will produce the following markup:

 <table>
  <tbody>
   <!-- ng-repeat-start='person in JSON.JSON.contact-info.phonebook'-->
   <tr ng-repeat="phone in person.phone">
    <td>{{ person.name }}</td>
    <td>{{ phone.phone }}</td>
    <td>{{ phone.number }}</td>
    <td>{{ person.nick }}</td>
   </tr>
   <!-- ng-repeat-end -->
  </tbody>
 </table>

An alternative approach could involve restructuring your original JSON data into a single-level list and employing a straightforward repeat loop.

 var allPhones = []

 _.each(json, (p) =>{ _.each(p.phone, (ph) => allPhones.push({
      name: p.name, 
      phone: ph.phone, 
      number: ph.number, 
      nick: p.nick})
 })

Once you have transformed the JSON, managing it with a simple ng-repeat on the Angular side should be feasible.

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

Pattern Update Method: Iteratively updating each individual node

I'm struggling to grasp the concept of updating only those d3 nodes where the data has changed. Despite my efforts, I still can't seem to get it right. In the test example provided below, I am noticing that everything is being updated instead of ...

Incorporate a pause into a JavaScript function

Consider the following function: $(document.body).ready(function() { var o = $(".hidden"); $(".about_us").click(function() { o.hasClass("visible") ? o.removeClass("visible") : o.addClass("visible"); }); }); I am looking to add a delay to this f ...

Server error occurs in NodeJS site when the MongoDB database is not empty

I am currently utilizing Node.js in conjunction with MongoDB and Mongoose to facilitate my database connectivity. An intriguing issue arises when the database lacks any values: the callback function successfully renders the subsequent page (albeit without ...

AngularJS page views functionality

After successfully setting up Mean JS on my system, I have been able to perform all CRUD operations flawlessly. However, I am facing a challenge in saving page views when a user visits a page. Whenever a user lands on a webpage such as /articles/:articleI ...

Tips for displaying the selectpicker once it is fully loaded

My webpage features a select element styled with the selectpicker plugin. However, upon loading the page, there is a brief period where the select area looks subpar. How can I ensure that the select is displayed only after it has been fully rendered by the ...

Element vanishing post JSON parsing

I have encountered an intriguing issue: I have developed an HTML/JS project that extracts information using XMLHttpRequest from the Scratch website. The main objective is to allow users to input their username and view their profile description on Scratc ...

Transform an SVG string into an image source

Is there a way to convert an incoming string ' ' into an img src attribute and then pass it as a prop to a child component? I attempted the following method, but it hasn't been successful. `let blob = new Blob([data.payload], {type: &apos ...

Minimize or conceal iframe

This iframe contains a Google form that cannot be edited. I am looking for a way to close or hide this iframe, either through a button, a popup window button, or without any button at all. The $gLink variable holds the Google form link through a PHP sessio ...

I am experiencing difficulties saving the html2canvas image

Trying to use html2canvas to take a screenshot of a div element and save it, but encountering issues with the saving process. function captureDiv() { const div = document.getElementById('myDiv'); html2canvas(div, { scale: 2, onrend ...

There seems to be an issue with the functionality of the JavaScript Quiz as it is

While working on my JS quiz, I encountered an issue where some answers were not displaying due to quotes and the need to escape HTML characters. Additionally, I am facing difficulty in accurately awarding points or deductions based on user responses. Curre ...

I encountered an issue while using the tab bar feature in Bootstrap where I wasn't able to navigate back to the first tab or any

My current project involves JavaScript, and I integrated a Bootstrap tab bar component. However, when I try to run the code in Google Chrome, I encounter an issue. The first time I select the first tab, the content displays correctly. But when I select the ...

Using jQuery to send a post request to a PHP script using either JavaScript or PHP

Just a quick question for those with experience. I am working on a page where I have implemented a jQuery AJAX post to another PHP page that contains JavaScript. My concern is, will the JavaScript code also be executed? Another scenario to consider is if ...

Using Node.js and Less to dynamically select a stylesheet source depending on the subdomain

Currently, my tech stack consists of nodejs, express, jade, and less. I have set up routing to different subdomains (for example: college1.domain.com, college2.domain.com). Each college has its own unique stylesheet. I am looking for a way to selectively ...

invoking a JavaScript function from .NET code-behind passing a specific value

Currently, I am facing an issue with calling a JavaScript function from my ASP.NET codebehind through the use of onclientclick for a link button. Here is how my code looks: string x = "redirectToImagePage"+"("+ y+")"; // The variable 'y' contain ...

ServiceNow allows users to access related tables and display them using JSON Web Services

I have been working on a C# project where I am extracting data from a ServiceNow database and converting it into C# .NET objects. To achieve this, I am utilizing the JSON Web Service to receive the data in JSON format. My goal is to establish a relational ...

Analyzing files that start with a period "."

I've come across a basic nodeJS script that reads files from a specific PATH and determines whether they are directories or not: var fs = require("fs"); var allFiles = fs.readdirSync(__dirname + '/bb'); allFiles.forEach(function(name){ if ...

Display or conceal div based on chosen options

I am working on a feature that involves three dropdown select boxes, each containing different sets of demographic attributes. My goal is to show a score based on the combination of selections made by the user. For example, if a user chooses Male, 18-24, A ...

Why isn't my redirection functioning properly?

My code is having an issue with the redirect function being called too early, causing the last file of a batch upload to fail. I've been searching all morning and trying different solutions without success. function uploadFile(something, callback) { ...

Navigating with Google Maps version 3 directions

Currently in the process of creating a new Google maps feature for my website, moving away from using v2. Everything has been smooth sailing up until the final step...after requesting directions on the map, there should be a visual line indicating the ro ...

commitment to a cyclical data framework

I'm facing a challenge where I need to resolve a recursive data structure before calling a controller. However, I am struggling to find the right approach to tackle this issue. Here is an excerpt of my current code: region.loadChildren = function() ...