Using a JSON nested loop to display both parent and child elements in Angular

I am in the process of developing a user interface that is dynamically generated based on the server response. I need to iterate to determine the number of tabs to be created and then iterate again to determine the amount of content to be placed within each tab. While I am able to generate the correct number of tabs, I am encountering issues with the number of inputs being generated. The JSON structure I am working with is as follows:

{
    "data": {
        "APIVersion": "2.0",
        "toplevelcontainer": [
            {"label": "value1", "type": "tabs", "key": "value1", "tooltip": "value1", "defaultValue": "value1",
               "content" : {
                    "innercontent": [
                        {"label": "tab1", "type": "input", "key": "value1","tooltip": "value1","defaultValue": "value1"},
                        {"label": "tab1", "type": "input", "key": "value1","tooltip": "value1","defaultValue": "value1"},
                        {"label": "tab1", "type": "input", "key": "value1","tooltip": "value1","defaultValue": "value1"},
                        {"label": "tab1", "type": "input", "key": "value1","tooltip": "value1","defaultValue": "value1"}
                    ]
                }
            },
            {"label": "value2", "type": "tabs", "key": "value2", "tooltip": "value2", "defaultValue": "value2",
                "content" : {
                    "innercontent": [
                        {"label": "tab2", "type": "input", "key": "value2","tooltip": "value2","defaultValue": "value2"}
                    ]
                }
            },
            {"label": "value3", "type": "tabs", "key": "value3","tooltip": "value3","defaultValue": "value3",
                "content" : {
                    "innercontent": [
                        {"label": "tab2",  "type": "input", "key": "value2","tooltip": "value2","defaultValue": "value2"}
                    ]
                }
            }
        ]
    }
}

I am now considering whether to utilize angular.forEach or ng-repeat. My forEach loop is structured as follows:

angular.forEach(data.data, function(top) {
  $scope.containers = top;
    angular.forEach(data.data.toplevelcontainer, function(lower) {
        $scope.inputs = lower;
    })
});

UPDATE: incorporating the ng-repeat method app.controller('TabController', function($scope, $http){

$http.get('data.json')
.success(function(data) {
    $scope.containers = data.data.toplevelcontainer;
    $scope.inputs = data.data.toplevelcontainer.content; //do I need to create a scope variable for each of these items I want to insert into the DOM?
})

Answer №1

Check out this basic tab system that is functional with the given data.

app.controller('MainCtrl', function($scope, $http) {
  $scope.model = {};// To avoid scope issues, add model properties to this object

  $http.get('data.json').then(function(resp) {
    $scope.data = resp.data.data
  })
});

HTML

<!-- Tabs -->
<ul>
   <li ng-repeat="tab in data.toplevelcontainer" ng-click="model.activeTab=tab">{{tab.label}} - Click me</li>
</ul>
<!-- Content-->  
<div ng-repeat="tab in data.toplevelcontainer" ng-if="model.activeTab == tab">
   <ul>
      <li ng-repeat="sub_tab in tab.content.innercontent">{{sub_tab.label}}</li>
   </ul>
</div>

Check out the demo

Answer №2

No necessity exists to establish variables within the scope for employing nested ng-repeat. The following code demonstrates how this can be achieved:

<div ng-repeat="item in data.toplevelcontainer">
    {{item.label}}
    <div ng-repeat="content in item.content.innercontent">
        {{content.label}}
    </div>
</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

`There is a delay in rendering the background image on Chrome`

Once I apply a class to my button element using JavaScript, the background image (.gif) that is supposed to display afterwards takes an unusually long time to render. The button serves as a form submission. Upon being clicked, a class of "clicked" is dyna ...

Failed to create WASM module: "module does not exist as an object or function"

I'm attempting to initialize a .wasm file locally within node.js in order to execute the binary on my local machine and mimic the functionalities of a webpage. Below is a simplified version of my setup: const fetch = require("node-fetch"); const impo ...

The submission of the Ajax form is malfunctioning

My attempt to load the php code without refreshing the page is failing with my Ajax code. What could be causing the issue? I prefer not to use jquery or other frameworks. Do you think the problem lies in my javascript code? Should I resort to using jquery ...

Mastering the Art of Binding Variables to Various JSON Types in GOLANG

When it comes to the naming convention of variables in a database, it is customary to use full_name. However, in Postman, the convention dictates using fullName instead. type Person struct { FullName string `json:"fullName"` } Nevertheless, ...

Display array values in JavaScript from different arrays

I'm currently working on extracting data from my API to plot it in a graph. Specifically, I am interested in obtaining an array that contains only the 'date' values. Here's what I have managed to extract so far: https://i.sstatic.net/0 ...

Leveraging Directives for Enhanced Leaflet Marker Functionality

Currently, I am conducting experiments involving AngularJS and Leaflet (I am still in the learning process with both). As part of this experimentation, I have noticed that I can define some HTML as a parameter in markers.bindPopup(...);. Has anyone attem ...

Need help with updating React component state within a Meteor.call callback?

I've constructed this jsx file that showcases a File Uploading Form: import React, { Component } from 'react'; import { Button } from 'react-bootstrap'; class UploadFile extends Component { constructor(){ super() this. ...

Guide to automatically sending users to a subdomain depending on their IP address location

Currently, my website is built using Node Express and I have a specific requirement. I want to redirect users to different subdomains based on their current location. For example, if a user in Singapore accesses site.com, they should be redirected to sg. ...

Text being enveloped in a span tag

Currently, I have a table displaying a list of users with their corresponding roles. However, the roles column is sometimes wrapping before reaching the end of the line. The user list data looks like this: $scope.userList = [{ "id": 1, "name":"AB ...

I am unable to log the response, but I can view it in Postman and the network tab

Currently, I am working on setting up a register feature with a specific endpoint. The challenge I am facing revolves around handling validation responses from the backend. For instance, if I attempt to register with a username that is less than six charac ...

Integrate ruby code within a javascript string

I am looking to insert tfx-<%= @doc.doc[:b].metadata['filename']} %> into a JavaScript string called 'url' url = "<%= @document.doc[:a].url(response_content_disposition: ContentDisposition.attachment( [INSERT HERE] )) %>"; ...

Troubleshooting JSON parsing issues in PHP

In reference to the discussion at: , where suggestions mainly revolved around JavaScript. Is there a specific function in PHP that can be utilized to address the issue described below and ensure that the output is valid JSON? Please note that using front ...

What is the best way to change JSON to tsv using the jq command in UNIX?

I'm looking to transform this JSON data into a TSV format. The source file I have looks like this: { "event": "log", "timestamp": 1535306331840, "tags": [ "info" ], "data": { "_id": "A301180827005852329209020", "msisdn": "628213 ...

Transforming a single object into several arrays

I have a JSON file called "icon.json" that contains the following data: [ { "name": "happy", "url": "1.gif" }, { "name": "excited", "url": "2.gif" }, { "name": "surprised", "url": "3.gif" ...

The callback function for ajax completion fails to execute

My current framework of choice is Django. I find myself faced with the following code snippet: var done_cancel_order = function(res, status) { alert("xpto"); }; var cancel_order = function() { data = {}; var args = { type:"GET", url:"/exch ...

Using Sequelize to send data from the client-side to the server-side

I am currently developing a project for a fictional library database and website interface. I am facing an issue where only 2 out of the 4 new loan form inputs are being passed to the req.body. Even though all items have a name attribute, it seems like onl ...

Modifying the order of Vuetify CSS in webpack build process

While developing a web app using Vue (3.1.3) and Vuetify (1.3.8), everything appeared to be working fine initially. However, when I proceeded with the production build, I noticed that Vue was somehow changing the order of CSS. The issue specifically revol ...

Employed Yeoman for Angular project setup using Gulp, facing issues with Protractor functionality

Subject pretty much explains it all. I am using OSX Yosemite and tried updating webdriver, chromedriver, and PhantomJS. Unfortunately, I keep getting this error: [15:41:30] Starting 'inject'... [15:41:30] gulp-inject 1 files into index.html. [15 ...

Having issues with your JQuery code?

I am attempting to locate a cell within a table that contains the class 'empty'. My goal is to then utilize a code snippet to obtain the id (cell number) and determine which cells are adjacent to it. As part of my test, I am experimenting with t ...

Discover results while inputting in the search box

Can anyone assist me? I'm looking to enhance my current code by adding a search functionality to the ul list. I want users to be able to type in a search term and have the matches automatically highlighted as they type, similar to a "find-as-you-type ...