How to showcase a list from intricate JSON data using Angular

I recently came across this pre-existing JSON data that I am unable to change:

{"tags": [
    {
      "title": "news",
      "options": [
          {
            "title": "important",
          },
          {
            "title": "less important",
          }
         ]
    },
    {
       "title": "entertainment",
       "options": [
           {
              "title": "entertainment",
           }
          ]
     }

My goal is to present this data in a list format, where titles with only one option should be displayed as-is, and titles with multiple options should show both the main title and its corresponding options. For example, based on the provided JSON, the desired output would be:

 <ul>
     <li>news<ul>
                <li>important</li>
                <li>less important</li>
             </ul>
        </li>
    <li>entertainment</li>
  </ul>

I am looking for a way to achieve this outcome using angularJS. Any suggestions or guidance would be greatly appreciated.

Answer №1

If you have a variable called myList in your AngularJS controller that holds a JSON object, you can use the following code to display nested data using ng-repeat. This code contains an outer ng-repeat looping through elements in myList.tags, and an inner ng-repeat looping through options within each element.

<ul ng-repeat="element in myList.tags">
    <li>
        {{element.title}}
        <ul ng-repeat="innerElement in element.options">
            <li>{{innerElement.title}}</li>
        </ul>
     </li> 
</ul>

Answer №2

If, by chance, the json data is housed within a variable named 'output'

<ul ng-repeat = "tg in output.tags">
   <li ng-if="tg.options.length > 1">{{tg.title}}
      <ul ng-repeat ="element in tg.options" >
         <li>{{element.title}}</li>
      </ul>
   </li>
   <li ng-if="tg.options.length==1">{{tg.title}}</li>
</ul>

Answer №3

Thanks to the suggestions above, I was able to find a clear solution to my problem. I had to nest two ng-repeat directives and add an ng-if statement to the inner loop.

This is what my final solution looked like:

<ul>
    <li ng-repeat="x in myData.tags">
        {{x.title}}
        <ul ng-repeat="y in x.options" ng-if="x.options.length > 1">
            {{y.title}}
        </ul>
    </li>
</ul>

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

Enhancing the appearance of HTML code within x-template script tags in Sublime Text 3 with syntax highlighting

I recently updated to the latest version of sublime text (Version 3.1.1 Build 3176) and have encountered a problem with syntax highlighting for HTML code inside script tags. Just to provide some context, I'm using x-template scripts to build Vue.js c ...

Comparison between WAMP and Live server integration with Facebook for connecting applications

I've been facing some challenges while integrating my website with Facebook Connect. I have been following the instructions provided in this guide. When attempting to run the following code from localhost, please note that for security reasons, my ap ...

Getting data from jquery.ajax() in PHP - A comprehensive guide

When transferring data from JavaScript to PHP, I use the following method: $.ajax({'url': 'my.php', 'type': 'POST', 'data': JSON.stringify(update_data), 'success': functio ...

Express: utilizing rawBody or buffer for a specific endpoint

I am looking to access the rawBody (buffer) specifically for a POST request on one route within my application. Currently, I have the following code snippet in my app.js: app.use(bodyParser.json({ verify: function(req, res, buf) { req.rawBody = buf; }})) ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

Build a Docker container for a project that requires utilizing yarn link for dependencies

While working on my NextJS project, I made the decision to utilize yarn as my package manager and utilized yarn link for import aliases/absolute imports. This feature of yarn is quite handy and is recommended for managing aliases within a project. However, ...

Encountering an issue while trying to pass hidden value data in array format to the server side

I am currently learning how to use Handlebars as my templating engine and encountering an issue with passing over data from an API (specifically the Edamam recipe search API). I am trying to send back the array of ingredients attached to each recipe card u ...

What is the best way to transmit information using the POST method in JavaScript?

When using javascript, the typical way to redirect a page with a parameter is the following: window.location = "add-new-cos.jsp?id="+id; However, the id value is sent to the next page using the GET method. I am interested in sending it using the POST met ...

What is the best way to reposition the origin of the canvas to the center?

As a beginner in html and JavaScript, I am currently working on a program that involves points and lines in a coordinate system. However, the canvas for html5 has its origin at the upper corner, and I need to create a coordinate system with the origin at ...

Using Node JS, how to pass a variable length array to a function?

Is there a way to dynamically call an addon function with varying argument lengths? I capture user input in a variable like this: Uinput = [5,3,2]; Now, I want to pass these numbers as arguments to my addon function like this: addon.myaddon(5,3,2); I n ...

Modify the button text when it is hovered over

I am attempting to modify the text displayed on a button when hovering over it in a React component from Ant Design. However, I have not been successful so far. Button <div className={ status == "verified" ? `${styles.btn1} ${styles.btn1C ...

Creating a Basic jQuery AJAX call

I've been struggling to make a simple jQuery AJAX script work, but unfortunately, I haven't had any success so far. Below is the code I've written in jQuery: $(document).ready(function(){ $('#doAjax').click(function(){ alert ...

The setCenter function in Google Maps is failing to properly center the map

I have implemented an Uber-like map feature in my Ionic/Angular mobile app where users can drag the map to select a location, with a marker always pinned in the center. I followed the steps outlined in this thread and this one to achieve this functionalit ...

Utilizing Loopback Callbacks within a Looping Structure

While working in a for-loop, I encountered an issue where I needed to access the loop variable 'i' from within a callback function but it was not accessible due to closure restrictions. Despite attempting different methods such as using (i) or ca ...

The Quickest Way to Retrieve Attribute Values in JavaScript

I'm trying to access a specific attribute called "data-price". Any tips on how I can retrieve the value of this attribute using this syntax: Preferred Syntax div[0].id: 48ms // appears to be the quickest method Alternative Syntax - Less Efficient ...

What is the best way to incorporate React hooks into a for loop?

I am looking to dynamically append a container with a specified number of div elements based on the data in a JSON file. I attempted to include the logic within a for loop, but encountered errors in the process. If you're interested in checking out t ...

Retrieving geographical data in GeoJSON format using AJAX request and displaying it on a Leaflet

I'm completely new to Leaflet and I'm struggling with how to integrate markers from a MySQL database onto a Leaflet map. Can anyone guide me on how to accomplish this using PHP and AJAX? .....{"type":"FeatureCollection","features":[{"geometry":{ ...

Navigating through nested arrays to access JSON objects

My attempts to retrieve the JSON data from this particular API have been unsuccessful. Every time I try to fetch the JSON, I am faced with a specific set of results as shown in the code below. const request = require('request'); var url = ' ...

Implement a loading bar on the entire page in Vue.js while a request is being made

There is an "edit" button on my page which allows me to edit certain elements and either save or close without saving. I would like to implement a loading bar that displays when the user clicks the "save" button, indicating that the data is being processe ...

Tips for passing parameters in an AJAX request

I have a single AJAX call that requires passing parameters to my function. Below is the AJAX call implementation: $.ajax({ url: 'lib/function.php', data: { action: 'getStoreSupplyItems', id: store_id, ...