Iterating through a nested array in AngularJS using ng-repeat

I am looking for a way to print out an infinitely deep array structure into a list. Below is the code snippet from a modified AngularJS example where I have added more nested children in the array. How can I display "child of child" and its subsequent children as well? Is there a method to repeat this process indefinitely as long as there are more children?

HTML

<div ng-app>
  <div ng-controller="TodoCtrl">
    <ul>
      <li ng-repeat="todo in todos">
        <span>{{todo.text}}</span>
        <ul>
          <li ng-repeat="child in todo.children">
            <span>{{child.text}}</span>
            <!-- What about the next one -->
          </li>
        </ul>
      </li>
    </ul>
  </div>
</div>

JS

function TodoCtrl($scope) {
  $scope.todos = [{
    text: 'root 1',
    children: [{
      text: 'child of root 1',
      children: [{
        text: 'child of child',
        children: []
      }]
    }]
  }, {
    text: 'root 2',
    children: []
  }];
}

Fiddle: https://jsfiddle.net/U3pVM/25866/

Answer №1

If you want to utilize the recursive view, follow this method:

<script type="text/ng-template" id="todo.html">
    <div>
        <div>{{ todo.text }}</div>
        <ul>
            <li ng-repeat="todo in todo.children" ng-include="'todo.html'"></li>
        </ul>
    </div>
</script>

<div ng-controller="MyController">
  <ul>
    <li ng-repeat="todo in todos" ng-include="'todo.html'"></li>
  </ul>
</div>

Check out the DEMO for a preview of how it looks with your provided data.

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

Creating a reusable function in AngularJS using the factory method

Currently, I am using the AngularJS factory method to retrieve data and passing that value to controllers. In order to avoid creating separate functions, I would like to create a common function that can be utilized in all controllers. How can I effi ...

What is the best way to generate a 3x3x3 blank matrix in JavaScript?

I am attempting to construct a 3*3*3 matrix where each element will hold a cube. Currently, all the cubes are arranged in a 1D matrix called all_cube. However, I need to organize them in a 3D matrix named cube[][][]. Below is the code for a more detailed ...

Editable JSON data within a table using Twitter Bootstrap

How come I am unable to utilize the bootstrap editable table in this manner? <table id="addElements" data-height="299"> <thead> <tr> <th data-field="id" data-align="right">Item ID</th> < ...

Mastering basic DOM manipulation in React with ES6 techniques

My goal is to update the header text when a button is clicked. After trying the code below, I noticed it doesn't work and there are no console errors: class Test extends React.Component { click() { $(".update").val("new value") } ...

Choose between using Paypal or Google Checkout for your shopping cart - unfortunately, both options cannot be used

My dilemma is that I currently have a functional shopping cart that is only coded for either Paypal or Google Checkout, not both. Here is a demo of the shopping cart set up for Paypal checkout: The javascript code used in the demo can be found here: Loo ...

The issue of recursion not functioning properly with ng-include and ng-repeat arises beyond the initial level

I am trying to iterate through an object in order to fill a table dynamically. To achieve this, I am utilizing ng-include and ng-repeat to loop through the object and generate a new <tr> for each element. However, I am encountering issues after the ...

NodeJS: The module failed to automatically register itself

Exploring the capabilities of IBM Watson's Speech to Text API, I encountered an issue while running my NodeJS application. To handle the input audio data and utilize IBM Watson's SpeechToText package, I integrated the line-in package for streami ...

Using Bootstrap 3's "img-responsive" class can cause images to become distorted when

When an image is rotated 90 degrees inside a modal, the img-responsive feature stops working and the image height exceeds the modal height. function rotateImage(){ var angle = ($('#testImg').data('angle') + 90) || 90; $(&apos ...

JavaScript: An object containing a unified handler for all method invocations

Let me explain further. Math.add(2, 2) //4 Math.multiply(4, 9) //36 Whenever a method in the Math object is invoked, it triggers a central processor that interprets the function name to determine its action. Can an object execute a default function when ...

Tips for extracting and manipulating JSON Data from an API in Python

In my Python script, I am trying to create a GitHub tool that extracts the following information: "stargazers_count": 2, << I require this number to be updated "watchers_count": 2, << I need this number to be updated "forks": 1, << I nee ...

What is the best way to assign a class to a span depending on the value of an object?

Check out my code snippet: <span class="msg" data-ng-show="question.message == 'Correct'" ng-class="{'green': question.message == 'Correct', 'red': question.message == 'Incorrect'}">{{ question.messa ...

Steps for registering a function on $rootScope when angularjs is ready

In order to make a method accessible throughout angularjs, I am looking to register it with 2 arguments (the resource id and the delete callback) using the resource provider to handle the deletion process. To properly register this method, I need angularj ...

Loading React router on every route page

<BrowserRouter> <div> <Route path={"/"} component={Home} /> <Route path={"/component"} component={AnotherComp} /> <Route path={"*"} component={NotFound} /> </div> </ ...

Customized Bootstrap navigation bar

I am a newcomer to Bootstrap and I'm attempting to create a three-column navigation menu with the nav-links centered in the middle. While using grids or flexbox, I could easily accomplish this in five minutes. However, for some reason, I am struggling ...

What makes JSONP a more secure option compared to JSON for cross-domain requests?

What is the reason behind browsers permitting cross-origin JSONP requests while prohibiting JSON requests for security purposes? Even though JSON requests are restricted to prevent XSS attacks, some may argue that JSONP could potentially pose a greater ris ...

Actuate the Puppeteer by either pressing the Enter key or clicking on the OK button within

Clicking OK button on dialog Having reached the end of my Puppeteer script, I am now faced with the task of clicking the OK button on a confirmation dialog box (refer to image linked above) or simply pressing the enter key. Despite attempting various solu ...

Error: The status property of the response is not a valid function within the POST method at line 19 in route.js for user sign up in the app

//server.js import {connect} from "@/dbConnection/dbConnection"; import User from "@/models/userModel"; connect(); export async function POST(request, response) { try { const {username, email, password} = await request.json( ...

Having trouble with the Google Calendar API?

I am in need of using the Google Calendar API to fetch event information from my calendar. I have set up my application and generated my server API Key. I have also inputted my IP address (since I am operating on my test server). Subsequently, I have cre ...

Using JavaScript, aim for a specific element by its anchor headline

I'm looking to make some changes to my navigation menu, specifically hiding the home menu item unless the mobile navigation menu is toggled. Is there a way for me to target the "home" anchor title and apply the active class to it when toggled, similar ...

Unable to convert date data for display on D3 line graph

I am attempting to replicate a line graph similar to the one in the following fiddle link: http://jsfiddle.net/wRDXt/2/ In the example, the date is used as new Date(2013, 17, 1). The JSON data I have is structured as shown below, [{ "_id": "bb68d8a2 ...