What is the correct method for ng-repeating through nested key-value pairs in AngularJS?

Explore the live code example:

Angular JS

Is there a way to effectively iterate through nested key-value pairs and display them as shown below?

The desired output should resemble a tree structure like this:

-touts
  -classes
    -col-12 
    -col-md-12
    -col-lg-12

However, the current output appears like this:

touts
  {"classes":["col-12","col-md-12","col-lg-12"]}

JavaScript Functionality:

var currentApp = angular.module('currentApp', []);
currentApp.controller('ACtrl', function($scope){

    $scope.templates = {
        'touts' : [
            {
                'classes' : ['col-12', 'col-md-12', 'col-lg-12' ]
            }
        ]
    };
});

HTML Structure:

<div ng-app="currentApp">
    <div ng-controller="ACtrl">
        <ul ng-repeat="(key, prop) in templates">
            <li>{{key}}</li>
              <li>
                  <ul ng-repeat="class in templates[key]">
                      <li>{{class}}</li>
                  </ul>
            </li>
        </ul>
    </div>
</div>

Answer №1

You are getting warmer, I made some updates to the fiddle. http://jsfiddle.net/y9wj6/9/

   <ul ng-repeat="(key, prop) in templates">
        <li>{{key}}</li>
        <ul ng-repeat="val in prop">
            <ul ng-repeat="(o, values) in val">
            <li>{{o}}</li>
                 <ul ng-repeat="i in values">
                      <li>{{i}}</li>
                  </ul
             </ul>
        </ul>
    </ul>

Answer №2

It's important to approach things step by step.


templates = {'cards' : [{'styles' : ['card-1', 'card-2', 'card-3' ] }]};  
// key = 'cards'
// properties = [{'styles' : ['card-1', 'card-2', 'card-3' ] }]
// properties[0] = {'styles' : ['card-1', 'card-2', 'card-3' ]}
// styleKey = 'styles'
// styleProp = ['card-1', 'card-2', 'card-3' ]
// display styleProp using ng-repeat

Here is a suggestion for you to try:

<div ng-app="currentApp">
   <div ng-controller="ACtrl">
        <ul ng-repeat="(key, properties) in templates">
            <li>{{key}}</li>
            <li>
               <ul ng-repeat="(styleKey, styleProp) in properties">
                  <li>{{styleKey}}</li>
                  <li>
                     <ul>
                         <li ng-repeat="style in styleProp">
                     </ul>
                  </li>
               </ul>
            </li>
         </ul>
    </div>
</div>

Answer №3

Although this question may be dated, by making a slight adjustment to the object (swapping array types for objects), the template below should function perfectly.

angular.module('init', [])
  .controller('test', ['$scope', function($scope) {

    $scope.templates = {
      'touts': {
        'classes': {
          'col-12': {},
          'col-md-12': {},
          'col-lg-12': {}
        }
      }
    };
  }]);
ul {
  list-style: none;
}
<script src"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="init" ng-controller="test">

  <script type="text/ng-template" id="recursive_item.html">
    {{key}}
    <ul>
      <li ng-repeat="(key, prop) in prop" ng-include="'recursive_item.html'"></li>
    </ul>
  </script>

  <ul>
    <li ng-repeat="(key, prop) in templates" ng-include"'recursive_item.html'"></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

JS implementing a listener to modify a Google Map from a separate class

Currently, I am in the process of migrating my Google Map functionality from ionic-native to JavaScript. I am facing an issue while attempting to modify the click listener of my map from a separate class. The problem seems to be related to property errors. ...

What is the best way to maintain an active listGroup even after reloading the page?

I'm currently working on a gallery project using the #listGroup bootstrap component. I would like to ensure that when a user clicks on one of the albums, the active state of the #listGroup persists even after the page is reloaded or refreshed. How can ...

Dynamically showcasing content in an HTML table

Having trouble with this code snippet. It's supposed to iterate through array objects and display them in an HTML table. The third row should have buttons, but nothing is showing up. Can you spot the issue? Here's the HTML code: <html> & ...

Modify the javascript addEventListener to use 'scroll' instead of 'wheel'

I am currently attempting to modify this javascript event to trigger on scroll instead of the mouse wheel. I have attempted to make the following changes: window.addEventListener('wheel',function (e) changed to window.addEventListener('sc ...

Dealing with undefined Angular UI Router resolve in controller due to data return from factory

Having trouble with Angular UI router? When returning a factory in resolve, why is the controller receiving undefined? What could be causing this issue? It works with string: When I return a simple string in the resolve function, I am able to get data in ...

A string was anticipated, however an object was encountered at line 3, column 4 in the document resulting in an

I recently implemented a post request method using Retrofit2, but I am facing an issue with the response that I receive. Expected a string but was BEGIN_OBJECT at line 3 column 4 path $.SUCCESS The expected response should look like: { "SUCCESS" ...

The error message "Undefined is not a function" is being thrown by the $onAuth function in Firebase's AngularFire Authentication

I've been working on updating an application to utilize the latest Firebase Authentication methods. Although most parts are functioning correctly, I encountered an issue while attempting this. myApp.controller('StatusController', function( ...

Fetching data from a collection using Mongoose in Node JS

Currently working with MVC architecture. Seeking guidance on using the findOne({}) method in my loginController. I need to retrieve data from an existing collection, which already contains some information. My goal is simply to extract data from it. Apolo ...

Determine if the "Privilege" array in JSON is set to "user" using

Here is the JSON data for my web server configuration: { "webserver_port": 80, "users": [ { "id": 1, "privilege": "Administrator", "username": "CorePack", "password": "$2b$10$xH5rvgSXbdnNsloKZeabFuC4wnhtxbIo4EeuzgdoiN/IOtrs ...

Updating databases with the click of a checkbox

Currently, I am developing a program for monitoring cars as part of my thesis. My current focus is on user management, and I have come across an issue where the database needs to be updated when the status of a checkbox changes. To visualize checkboxes, y ...

Removing a SubDocument from an Array in Mongoose

For my project, I am utilizing mongoose to create a database. The schema for my Class looks like this: const mongoose = require('mongoose') const classSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, consultant: { type: mo ...

The serialization of a ManyToMany through field

I am experiencing difficulties when it comes to serializing my items/orders along with their quantities. The current results I am obtaining are as follows: { "id": 1, "_current_status": null, "orderitem_set": [ { "item_id": 2, "quanti ...

Having trouble with jQuery toggle fade: Unable to make the div fade in/out when toggling

Is there a way to modify the functionality of my black button so that when clicked, the red div fades out while the blue div fades in? Right now, clicking the button switches between the two divs without any fading effect. Fiddle: http://jsfiddle.net/ddac ...

Minimize an array by organizing objects based on the proximity of their numbers

My array contains the following data: [ { "begin": 870, "end": 889, "spanType": ["plan", "gt-plan"] }, { "begin": 890, "end": 925, "spanType": ["plan", "gt-plan"] }, { "begin": 926, "end": 938, "spanType": ["plan", "gt-plan"] }, { "begin": 939, ...

Generating JSON data with Ruby for a collection of items

I'm a beginner with Ruby. My goal is to generate a JSON file for a set of elements. To achieve this, I am utilizing the each function to fetch the data. The desired structure of the JSON file for a 4 element array is as follows: '{ "desc" ...

I am attempting to convert a JSON file that contains several nested arrays into a CSV file using Powershell

I'm attempting to convert a json file to a csv file using Powershell. The json file I'm working with contains multiple nested arrays that I want to expand. Below is the file structure and the code snippet I'm using: Here is a glimpse of the ...

The function validateLogin is not defined within the code, resulting in a javascript exception being

Hey there, I'm encountering an undefined function error and I believe my code is correct. Can someone please offer assistance in this situation? Additionally, could you recommend a good tutorial for fetching data through a webservice using the Ajax me ...

Creating a multi-line string of JavaScript within a Perl script

I am currently working on creating a unique JavaScript string using q{} like this: my $javascript = q{ $(function () { var chart; $(document).ready(function () { // Build the chart $(&b ...

Interactive state for associated product within list without order

I am currently working on a project that involves an unordered list with separate list items. The menu design includes product images in the top list item and the corresponding product names in the list item below. I have successfully implemented a hover s ...

Converting JSON information into a table format for easy viewing

How can I extract the first timestamp value from the initial row using C# along with Newtonsoft.Json? Is it possible to showcase this information in a table comprising of headers such as beaId, bfiId, timestamp, beaName, and bfiName utilizing Angul ...