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

Encountering ENOENT error with Node.js file preview

I am attempting to utilize the filepreview tool to extract an image from a docx document. I have successfully installed it using the command npm install filepreview. This is the code snippet I am working with: const filepreview = require('fileprevie ...

Iterate through an array, mapping the values and then returning a

Look at the code provided: const { aForm, bForm, eForm, qForm, } = this.form; return ( aForm.isEditing || bForm.isEditing || eForm.isEditing || qForm.isEditing ); Can we optimize this in a different ...

Vue component not receiving the updated prop value from parent component

I am encountering a problem with my parent-child component setup. The issue arises when I pass a validation field as a prop from the parent to the child, but it doesn't update upon the first click of the submit button in the child component. To explai ...

Karma is reporting an error with TypeScript, saying it cannot locate the variable 'exports'

Currently, I am in the process of mastering how to write Unit Test cases for an angular project coded in Typescript. To facilitate this, I have opted for utilizing Karma and Mocha. Below lays out the structure of the application: Project/ ├── app/ ...

jQuery click event handler performing no action

I am encountering an issue with the input on my index page: <input type="button" name="goReplaceAll" value="Go" id="allReplaceGo" style="cursor:hand;" /> There is an onclick call from jQuery as follows: $(document).ready(function() { $(&ap ...

The validation process in reactive forms is experiencing some issues with efficiency

Trying to debug an issue with my reactive forms - the repeatPassword field doesn't update as expected. When entering information in the "password" field, then the "repeatPassword" field, and back to "password", the second entry is not flagged as inval ...

Modify the data values and reconstruct the JSON structure using Python

I'm facing a situation where I need to work with the following json data: data = { "app": [ { "ida": 10, "configur": { "config": [ { "active": "true", "tol": ...

When deciding between .attribute=, setAttribute, and attr(), which is the best option to use?

.attribute in Javascript let friendDiv = document.getElementById("friend"); friendDiv.className = "list"; VS setAttribute in Javascript let friendDiv = document.getElementById("friend"); friendDiv.setAttribute("class","list"); VS .attr in Jquery $(" ...

When the menu active item is clicked, the header will automatically scroll to the top

I've implemented a sticky header using CSS and JavaScript along with a mega menu. However, I've encountered an issue where when scrolling to the bottom and clicking on the "more" link in the dropdown, the page scrolls back to the top. This is the ...

JavaScript and HTML are commonly used programming languages for developing

By utilizing JavaScript, I was able to generate a table dynamically based on user input. For example, if the user enters 3 and clicks "go", a table with 3 rows is created. Using the .keyup function allowed me to target a column successfully. However, an i ...

A warning has been issued: CommonsChunkPlugin will now only accept one argument

I am currently working on building my Angular application using webpack. To help me with this process, I found a useful link here. In order to configure webpack, I created a webpack.config.js file at the package.json level and added the line "bundle": "web ...

JQuery Ajax encounters a 500 error message due to an internal server issue

I'm currently using the jQuery library to send an ajax request to a PHP file. Initially, everything was working perfectly fine with a relative path like this: url:"fetch_term_grades.php", However, when I modified the path to be more specific like th ...

The art of representing objects and generating JSON responses

As I dive into building a web application using NextJS, a versatile framework for both API and user interface implementation, I find myself pondering the best practices for modeling and handling JSON responses. Key Points In my database, models are store ...

Exploring AngularJS and Jasmine for testing a factory component

I am currently learning about unit testing in AngularJS. I have a factory that I am trying to spy on using Jasmine, but I am having trouble figuring out the correct syntax for the test spec. Below is the code snippet for the factory: app.factory('ass ...

Exploring the power of jQuery closures and handling events like mouseover and mouseout

I'm currently grappling with the concept of utilizing closures in conjunction with jQuery event functions. The challenge I am facing involves creating rounded shapes on the screen that stop and fade when hovered over, then resume fading when the mous ...

Using Grails to create remote functions with multiple parameters

Currently, I am able to send one parameter to the controller using the code snippet below in Javascript: <g:javascript> var sel = "test"; <g:remoteFunction action="newExisting" method="GET" update="updateThis" params="'sel='+s ...

Google Extension PHP Plugin

Is it feasible to integrate a PHP file into a Google Extension for Chrome? I've been exploring the idea of creating an extension and most resources only mention HTML, CSS, and JavaScript. Any guidance on using PHP in the extension would be highly valu ...

Utilizing X-editable in an ASP MVC View: navigating the form POST action to the controller

I have been utilizing the X-Editable Plugin to collect user input and perform server submissions. However, I am encountering an error during submission. What adjustments should I make in order to ensure that the x-editable data functions properly with the ...

"Utilize Ajax to load PHP content and dynamically refresh a specific div

I have implemented an image uploading system, but now I want to incorporate a feature that allows users to rotate the uploaded images using Ajax. The challenge I'm facing is that if the session variable is lost during a full page update, I need to ens ...

Parse the JSON string into a list of C# objects when the string is received as NULL in the request

I'm currently working on a code snippet that converts a JSON string into a list of objects: public class rest_all { public string restaurants { get; set; } } public class rest_all_data { ...