Managing dynamic JSON responses in an Angular template

Looking for a solution to handle dynamic JSON responses using a single angular template? Check out these two examples of the same template with different JSON responses, both somewhat similar. How can we handle unknown levels in a JSON response within the same template?

Example 1

{"book": {
        "title": "Book Title",
        "chapters": [
            {
                "title": "Chapter One",
                "units": [
                    {
                        "title" : "Unit One",
                        "sections": [
                            {"title" : "Section One"},
                            {"title" : "Section Two"},
                            {"title" : "Section Three"}
                        ]
                    },
                    {"title" : "Unit Two"},
                    {"title" : "Unit Three"}
                ]
            },
            {"title": "Chapter Two"},
            {"title": "Chapter Three"}
        ]
    }};

Example 2

{"book": {
        "title": "Book Title",
        "chapters": [
            {
                "title": "Chapter One",
                "sections": [
                            {"title" : "Section One"},
                            {"title" : "Section Two"},
                            {"title" : "Section Three"}
                        ]
            },
            {"title": "Chapter Two"},
            {"title": "Chapter Three"}
        ]
    }};

Template to handle these responses:

  <div ng-repeat="item in book">
    {{item.title}}
    <ul>
          <li ng-repeat="chapter in item.chapters">
            {{chapter.title}}
          <ul>
            <li ng-repeat="unit in chapter.units">
              {{unit.title}}
              <ul>
                <li ng-repeat="section in unit.sections">
                  {{section.title}}
                </li>
              </ul>
            </li>
          </ul>
        </li>
        </ul>
  </div>

Answer №1

<div>
  {{ book.title }}
  <ul>
    <li ng-repeat="chapter in book.chapters" ng-if="book.chapters.length > 0">
      {{ chapter.title }}
      <ul>
        <li ng-repeat="unit in chapter.units" ng-if="chapter.units.length > 0">
          {{ unit.title }}
          <ul>
            <li ng-repeat="section in unit.sections">
              {{ section.title }}
            </li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</div>

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

How do you set a default value for a dropdown menu (<select>) and then update it later on?

In my grid, each row has a dropdown menu and I want to display its state from the database. The dropdowns are defined with a selected option specified for preselecting the value from the DB. <select id='selectId'> <option value='1& ...

How to make a Python script showcase JSON information

I need some guidance on extracting the "name" value from a JSON file using a Python script. Here is an example snippet of the JSON data: "restaurants": [ { "restaurant": { "R": { "res_id": 9101083 }, "id": "9101083", "name": "My Me ...

Encountering the error message "Function 'this._initialize' is not defined" when utilizing the mangojs module

Check out my code snippet below: const express = require("express"); const router = express.Router(); const mangojs = require("mangojs"); const db = mangojs('mongodb://***:***@XXXXXX.mlab.com:43900/tasks', ['tasks']); router.get("/tas ...

Nestjs struggles with resolving dependencies

Having trouble finding the issue in my code. (I'm still new to nestjs and trying to learn by working on some apps). The console log is showing the following error: Nest can't resolve dependencies of the UrlsAfipService (?). Please ensure tha ...

Parsing complex JSON data in Go using unmarshal

I am looking to decode the provided JSON data in Golang: { RESPONSE : { CODE : "123" NEW_RESPONSE :{ 0:[ { key1:val1, key2:val2 }, { ...

Utilizing JavaScript to transmit checkbox values to a database

I am both intrigued and confused by the power of checkboxes. I want to use them to allow customers to select their preferred type of cuisine (fast food, Italian, sushi, etc.). Ultimately, I plan to match these preferences with restaurants offering those ty ...

Struggling with Sequelize's refusal to add new records to the database

In my backend server, there is a function defined as follows: async create(data) { try { console.log("User ", data); const newUser = await models.User.create({ ...data, password: await bcrypt.hash(`${data.password} ...

Assign custom controller to angular directive

Here is a directive code snippet: <list source="userList" avatar-url="avatarPath" search="search"></list> The directive is defined as follows: .directive('list', function($rootScope) { return { restrict: &a ...

Guide to customizing the default scrollbar colors in Nextjs

When browsing websites like tailwindcss.com or https://developer.mozilla.org/ in Chrome and Firefox, you may have noticed that they utilize the default scrollbar style but allow users to change its colors through a dark/light mode button. The appearance of ...

Exploring the retrieval of JavaScript array elements from a ListModel within QML

Currently, I have some JavaScript data that consists of a list of objects containing other objects and arrays, which I want to append to a ListModel. This is what the structure looks like (assuming that the data is generated elsewhere and its structure sh ...

Is there a way to determine which elements have been hidden or shown using Bootstrap 4 collapse events?

Looking to enhance the functionality of a Bootstrap 4 accordion, I am exploring the possibility of utilizing their events (https://getbootstrap.com/docs/4.0/components/collapse/#events). In one of their examples, $('#myCollapsible').on('hid ...

What is the best way to apply the 'active' class to a selected navigation link using JavaScript?

How can I use JavaScript to change the active click of a Bootstrap navbar based on which nav link was clicked? The issue is that the changes made by JavaScript are lost when the browser navigates to the corresponding page. MY CODE: document.querySelect ...

What is the best way to structure a JSON response in python code?

Here is a sample of my JSON data: data = [{"document_id":"FT_3860001798686","party_type":"1","name":"LEE, GABRIEL"},{"document_id":"FT_3860001798686","party_type":&qu ...

When attempting to use the .split method, an error is thrown stating that addEventListener is not

I'm attempting to create a table that automatically fills in the next input when I select options from MySQL. However, when I run this code, I get an error saying "addEventListener is not a function." I'm not very familiar with JavaScript, so I&a ...

Crafting JSON using the jq tool

I need help creating a JSON file using jq from the output of the "lsb_release" command. This is what I've tried: if [ -x "$(command -v lsb_release)" ]; then lsb_release -a | jq --raw-input 'split("\t") | { (. [0]) : . [1] }' > ...

Issue with Bootstrap 5: Navigation feature struggling in carousel

I am currently using bootstrap 5 and looking to incorporate an image carousel and a modal into my project. Here is the sample code I have: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Increase in JQuery .ajax timeout not effective

My website has a process where JavaScript sends a POST request to a PHP server using the .ajax() function. The PHP server then communicates with a third-party API to perform text analysis tasks. After submitting the job, the PHP server waits for a minute b ...

Automatically logging in to a website using an AngularJS form

I am struggling with autologin to a website that has an authentication form built with Angular JS. The form structure looks like this: <form name="loginForm" class="login-form ng-pristine ng-invalid ng-invalid-required"> <div class="tight-fo ...

Ways to switch out error message for an error landing page

I am currently displaying error text when something goes wrong, but I would like to enhance the user experience by redirecting to a well-designed error page instead. Can anyone provide guidance on how to achieve this? Below is my existing code for display ...

Is it possible to attach an onclick event to modify a data point in Chart.js?

Currently using chartjs for a small project and facing some challenges with editing data points. Is there a built-in function in this library that allows me to bind an onclick event for displaying a pop-up and removing the point? This is what I am lookin ...