Creating a nested list in AngularJS using the ng-repeat directive

My experience with AngularJS is limited, but I am tasked with modifying a web app that requires nesting lists inside each other:

<ul class="first-level">
  <li ng-repeat="item in list">{{item.parentNo1}}
     <ul class="level-2">
       <li ng-repat="item in list">{{item.childOfCurrentParent}}</li>
       . . .
     </ul>
  </li>

  <li ng-repeat="item in list">{{item.parentNo2}}
     <ul class="level-2">
       <li ng-repat="item in list">{{item.childOfCurrentParent}}</li>
       . . .
     </ul>
  </li>
</ul>

A JSON array of objects was provided to me in the following format:

[{
    "id": 53,
    "nazwa": "Plafon Nekko",
    "foto": "01/01 _ Koma Nekko.jpg",
    "visible": 0,
    "cat_id": 1,
    "strona": 1,
    "styl": "nowoczesny",
    "rodzina": "Nekko",
    "kod": "O2177",
    "bookmark": true,
    "title": "nowoczesny Nekko",
    "page": 1,
    "image": "/lemir/www//gazetka/01/01 _ Koma Nekko.jpg",
    "width": 849,
    "height": 1201,
    "tags": "nowoczesny Koma O2180 Plafon Koma nowoczesny Koma O2181 Plafon Koma nowoczesny Koma O2182 Plafon Koma nowoczesny Koma O2183 Plafon Koma nowoczesny Koma O2184 Plafon Koma nowoczesny Koma O2185 Plafon Koma nowoczesny Koma O2186 Plafon Koma nowoczesny Koma O2187 Plafon Koma nowoczesny Nekko O...
},...]

I must arrange the parents at the first level and their children at the second level. A new parent should create another first-level li. Additionally, I need to link the style property (parent) with the name property (child).

Is there a way to make ng-repeat return to the first level when encountering a new parent value?

Answer №1

Although the question may be a bit dated, I believe I have found a great solution for handling nested lists. In my opinion, it provides a cleaner approach.

If you're interested in learning more about recursive templates in Angular, check out this blog post:

angularjs-recursive-templates

Check out the hierarchical list structure below:

[ 
{ 
    title: 'Computers',
    categories: [
      {
        title: 'Laptops',
        categories: [
          {
            title: 'Ultrabooks'
          },
          {
            title: 'Macbooks'            
          }
        ]
      },
      {
        title: 'Desktops'
      },
      {
        title: 'Tablets',
        categories: [
          { 
            title: 'Apple'
          },
          {
            title: 'Android'
          }
        ]        
      }
    ]
  },
  {
    title: 'Printers'
  }
]

Take a look at the Angular sample provided:

<!-- recursive template -->
<script type="text/ng-template" id="categoryTree">
    {{ category.title }}
    <ul ng-if="category.categories">
        <li ng-repeat="category in category.categories" ng-include="'categoryTree'">           
        </li>
    </ul>
</script>
<!-- use -->
<ul>
     <li ng-repeat="category in categories" ng-include="'categoryTree'"></li>
</ul>

For a live demonstration, visit this JSFiddle link.

I hope this information proves helpful to some individuals.

Goodbye!

Answer №2

In order to improve the functionality, my recommendation is to handle this particular scenario within the model itself rather than on the frontend.

You have the option to create two customized functions that will return the model in the required format.

Subsequently, you can utilize these functions as shown below:

<ul ng-repeat="parent in fetchParents(data)">
    ...
    <ul ng-repeat="child in fetchChildren(data, parent)">
        ...

Alternatively, if you possess the ability to modify the Json structure, a more straightforward solution would be to alter it according to your specifications. You could transform it into an array of parents, each having an associated array of children.

This adjustment would simplify the process significantly, similar to the following example:

<ul ng-repeat="parentItem in data">
    ...
    <ul ng-repeat="childItem in parentItem.children">
        ...

Answer №3

If you want to achieve something similar to this, consider adding an array of children to your JSON data and then iterating through it.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.list = [{
    "id": 53,
    "nazwa": "Plafon Nekko",
    "foto": "01/01 _ Koma Nekko.jpg",
    "visible": 0,
    "cat_id": 1,
    "strona": 1,
    "styl": "nowoczesny",
    "rodzina": "Nekko",
    "kod": "O2177",
    "children": [{
      "name": "xyz",
      "age": "15"
    }, {
      "name": "pqr",
      "age": "10"
    }],
    "tags": "nowoczesny Koma O2180"
  }];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <ul>
    <li ng-repeat="parent in list">{{parent.nazwa}}
      <ul>
        <li ng-repeat="child in parent.children">{{child.name }}</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

Prevent memory leakage by utilizing Angular's $interval feature in countdown processes

I have a controller set up to handle a countdown feature: var addzero; addzero = function(number) { if (number < 10) { return '0' + number; } return number; }; angular.module('theapp').controller('TematicCountdownCo ...

What could be the reason behind TypeScript ignoring a variable's data type?

After declaring a typed variable to hold data fetched from a service, I encountered an issue where the returned data did not match the specified type of the variable. Surprisingly, the variable still accepted the mismatched data. My code snippet is as fol ...

Stop the interval once the route is altered in Angular 2

After initiating a timer within an Angular 2 component located inside a router outlet, I encounter a problem when switching routes. The timer continues to run even after leaving the route. How can I ensure that the timer is properly stopped upon route ch ...

Select a random object from a document and dispatch it. A Discord bot

I'm looking to enhance my bot by adding a command that retrieves a random quote from a JSON file and displays it in chat. I've already figured out how to do this using an array, but I'm not sure how to pull the quotes from a file. EDIT: ...

Tips for detecting the creation of an iframe before executing any javascript code

Before executing some JavaScript, I am trying to wait for an iframe to be created. I have attempted several methods, but none seem to effectively wait for the iframe. The console error that keeps appearing is Uncaught (in promise) TypeError: Cannot read pr ...

Transmitting an array to JSON in PHP

These arrays need to be converted into JSON format: { "1JzSZFs2DQke2B3S4pBxaNaMzzVZaG4Cqh": 100000000, "12Cf6nCcRtKERh9cQm3Z29c9MWvQuFSxvT": 1500000000, "1dice6YgEVBf88erBFra9BHf6ZMoyvG88": 200000000 } Struggling to achieve this in PHP, a ...

Comparing obj.hasOwnProperty(key) with directly accessing obj[key]

Consider the scenario where I need to determine if a property exists within an Object. A comparison between two methods caught my attention: if(object.hasOwnProperty(key)) { /* perform this action */ } OR if(object[key]) { /* perform this action */ ...

Display elements in an array of objects when the value changes with React

In my code, I am working with a nested list where each element has child nodes including id, name, and ancestors. The ancestors node contains an array of names and ids of the parent node, grandparent node, and so on. Here is an example: { "name": "Chi ...

What's causing the show/hide feature to malfunction within the for loop in Vue.js?

I've encountered an issue with my for loop where the show/hide functionality doesn't seem to work despite everything else functioning properly. I've been trying to troubleshoot this problem without success. <div id="app"> <ul> ...

Displaying divs depending on dropdown selection - Troubleshooting script issue

When I try to display certain divs based on dropdown selection using the script below, it works fine on a simple page. However, when I implement it on my current development page, it completely messes up the layout, turning everything black and adding stra ...

Tips for positioning D3 circles along a half-circle arc

I'm trying to align a series of radios in a semi-circle formation, created from circles. The number of radios will vary and I need to ensure they stay centered. Here is my current setup: UPDATE: I just noticed that the order of the radios in the scre ...

Storing POST Request Data in Express

I want to use a single API endpoint for both GET and POST requests. My goal is as follows: Send multiple POST requests to /api/users with data like: {'id': 2, is_valid: 'true'} Retrieve this data by fetching the same API URL later on ...

Creating hierarchical tables in PostgreSQL

I have a dataset in JSON format that is structured as an array. I need to create a table in Postgres-SQL and store this data within it. Dealing with such complex data is new to me, so I am finding it challenging to map the columns to their corresponding va ...

The text/font-weight of the header button is mysteriously shifting without warning

While creating a header for my webpage, I encountered an issue where the text family was changing when the dropdown menu was launched in Safari 8. Curiously, this behavior did not occur when using Chrome to launch the jQuery function. Even after attempting ...

Setting the locale in an extended datapipe in Angular 4: A step-by-step guide

I have created a custom pipe by extending the DataPipe Angular class. import { Pipe, PipeTransform } from '@angular/core'; import { DatePipe } from '@angular/common'; @Pipe({ name: 'dateTimeFormater' }) export class DateTi ...

Is there a browser-friendly alternative to `fs.readFileSync` function?

When I use fs.readFileSync to read a wasm file in Node, I am able to get the file in the desired format. However, when I attempt the same process in the browser using the FileReader, the format seems to be incorrect. Why does this happen? Is there an equi ...

Manipulate the DOM elements within the ng-repeat directive

Hello, I am currently new to AngularJS and have just begun learning how to create directives. While working on a sample project, I encountered an issue with accessing DOM elements rendered inside my directive. Some elements were not accessible in the link ...

Why is the Express validator failing to work with the posted value?

I have come across an issue with my current code. Everything is working fine, but I need to access req.body.type in the createValidationFor function. However, when I try to access it, the validation stops working and I can't figure out why. router.po ...

Using JavaScript in Ext JS 4, transform a JSON object into a different JSON object

What is the simplest way to transform JSON A into JSON B using JavaScript? JSON A: { "d": [ {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"0","value":"one"}, {"__type":"Web.Controls.Shared.GeneralServic ...

Utilize jq to extract data from json output

Thank you for your continued support. I am facing an issue with converting a JSON output into CSV format. While I have managed to generate some output, it does not align with the desired outcome. Curl Command Output { "results": [{ "name ...