Retrieving data from a nested object with varying key names through ng-repeat

My JSON object contains various properties with unique names:

var definitions = {
  foo: {
    bar: {abc: '123'},
    baz: 'def'
  },
  qux: {
    broom: 'mop',
    earth: {
      tree: 'leaf',
      water: 'fish'
    },
    fig: {
      qwerty: 'olive'
    }
  },
  blix: {
    worm: 'dirt',
    building: 'street'
  }
  ... more nested objects
};

Currently, I am displaying this data in the following way:

<div class="type" ng-repeat="(key,val) in definitions">
  <h4 ng-model="collapsed" ng-click="collapsed=!collapsed">{{key}}</h4>
  <div ng-show="collapsed">{{val}}</div>
</div>

Below is my controller code:

App.controller('DefinitionsCtrl', function ($scope) {
  $scope.definitions = definitions;
});

The {{val}} currently displays a condensed string of the property when its corresponding {{key}} is clicked. I want to further parse the val section, so that for example, the nested properties of foo (such as bar and baz) each have their own respective divs. This should apply to all nested values. Since manually doing this is not feasible due to the file size, I need a more efficient solution.

Is it possible to achieve this given that all the nested property names are unique? Would I need to create a custom filter, or should this be handled within the controller?

Answer №1

It seems like you're looking for a way to implement recursive ng-repeat in AngularJS. One approach is to create a custom directive.

Take a look at this example of a recursive directive:

.directive('collection', function () {
return {
    restrict: "E",
    replace: true,
    scope: {
        collection: '='
    },
    template: "<ul><member ng-repeat='member in collection' member='member'></member></ul>"
}
})

.directive('member', function ($compile) {
return {
    restrict: "E",
    replace: true,
    scope: {
        member: '='
    },
    template: "<li>{{member.name}}</li>",
    link: function (scope, element, attrs) {
        var collectionSt = '<collection collection="member.children"></collection>';
        if (angular.isArray(scope.member.children)) {       
            $compile(collectionSt)(scope, function(cloned, scope)   {
                element.append(cloned); 
              });
        }
    }
}
})

You can see it in action here: http://jsbin.com/acibiv/4/edit and read more about it in this blog post: , although the code in the blog post has some mistakes related to compilation.

Certainly, you will need to customize this solution according to your specific needs. Instead of checking for "children", make sure to adjust the code based on your objects structure.

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

Tips for effectively creating and appending elements using JavaScript

Code Sample var result=$.getJSON("http://search.twitter.com/search.json?callback=?",{q:query}, function(data) { ... question. }); Query: In order to display each tweet result, I want to ...

Leveraging the power of JavaScript's .map(...) method in a

Within my React code, I have a structure similar to the following: {elements.map((element) => { return ( <div> {renderDate(element.date)} </div> ) }})} This structure calls the renderDate function defined as: co ...

Retrieving Posts from Extensive JSON Data

I'm currently working on a project where I am coding a system to monitor updates on the Ontario Immigrant Nominee Program Updates page and then send out email alerts whenever a new article is posted. Initially, I implemented this in PHP but now I want ...

Gatsby is throwing an error because the location props are not defined

I am attempting to utilize location props in my Gatsby page. In pages/index.js, I am passing props within my Link: <Link state={{eventID: event.id}} to={`/date/${event.name}`}> </Link> In pages/date/[dateId]/index.js: const DateWithId = ( ...

Overriding a shared module service in Angular from a separate module: A step-by-step guide

I am working with various modules such as SchoolModule, UniversityModule, and SharedModule The SharedModule includes a BaseService that both the SchoolModule and UniversityModule providers are utilizing as an extension When loading the SchoolModule, I ne ...

Show the cell data when the checkbox next to it is selected

I have a specific table setup and I am trying to display the content of the table cell if its corresponding checkbox is checked upon clicking a button. For example: If Row2 is checked, an alert box should display Row2 Below is my code snippet, Java ...

Stop the Enter key from functioning as a mouse click

Whenever an element is focused on and a mouse click action can be triggered, I've observed that the Enter key functions as if you're clicking the mouse left button. This behavior is causing conflicts in other parts of my code, so I need to find a ...

Executing a command efficiently in Javascript with the get method

The command that needs to be sent to the embedded device is in the form of a GET method. However, the value continuouspantiltmove: String(pt) is not being properly transmitted to the CGI script through Google Chrome, causing it to fail. Since I do not hav ...

How do I ensure that a nested <button> in AngularJS does not submit the form it is contained in?

My current project involves a form in AngularJS used for inputting data into a movie database. The form includes a dropdown menu allowing users to select actors to add to the movie record they are creating. However, when the user clicks the button next t ...

Troubleshoot my code for clustering markers on a Google map

I'm currently working on a piece of code to generate a Google map that contains 3 hidden points within one marker. The idea is that when the main marker is clicked, these points will either merge into one or expand into 3 separate markers. However, I& ...

Steps for creating a comment with WP Rest API v2

I'm attempting to generate a fresh comment through the WP Rest APi v2 by sending a POST request to this specific URL: https://www.turboweb.online/wp-json/wp/v2/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2a1adafafa7acb ...

Automatic page switch upon dropdown selection

I'm not very proficient in JavaScript and I want to modify a form so that it automatically updates when a dropdown option is selected, without needing to click a separate "Go" button. How can I adjust the code below? It contains three different dropd ...

Unable to $delete within nested angularfire controllers

Utilizing angularfire, I am managing a series of online courses where each course contains multiple lectures. I have structured the lectures as nested within their respective courses. The factory I have implemented successfully enables CRUD operations for ...

Steer clear of chaining multiple subscriptions in RXJS to improve code

I have some code that I am trying to optimize: someService.subscribeToChanges().subscribe(value => { const newValue = someArray.find(val => val.id === value.id) if (newValue) { if (value.status === 'someStatus') { ...

What is the best way to convert my Chatbot component into a <script> tag for seamless integration into any website using React.js?

I have successfully integrated a Chatbot component into my Next.js application. https://i.stack.imgur.com/BxgWV.png Now, I want to make this component available for anyone to use on their own website by simply adding a tag. My initial approach was to cre ...

Storing HTML elements in a database using jQuery's html() method

I have encountered a dilemma that has left me stumped after extensive online research. I have a dynamically generated webpage and need to save the entire appended body of the page to a database using PHP and MySQL. My current approach involves using the fo ...

Having trouble accessing a DOM element within a Vue component while using vanilla JavaScript

I am attempting to dynamically update data from a Vue component using jQuery in a Webpack project. Below is the code snippet: <template> <div id="container"> <slot>show string!!</slot> <div id="s_container"&g ...

Sending search queries from a frontend built with React.js to a backend in Express.js: What is the best approach?

I have been attempting to develop a basic search bar using react.js that will communicate with my express.js backend in order to retrieve the accurate data from the database and display it on the front-end. However, I am struggling to grasp how to transmit ...

Is there a way to display the "back button" on a subview?

As a newcomer to Ionic, I am finding navigation to be the most challenging aspect. My app has two tabs - "Dashboard" and "Friends". When I click on the Dashboard tab, I want it to navigate to a subview called "subview_dash", without displaying the tabs in ...

How can I load a function from the HTML file that is being loaded using .load() in jQuery?

Within my main window main.html, there is a div button that, when clicked, loads another html file into a large div. This is achieved using the .load() function: $('#mainpanel').load("search.htm"); The "search.htm" file contains a function cal ...