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

I am puzzled as to why my Details Modal keeps appearing whenever I click anywhere, even when I have specifically added it to only show up on the event of today. Additionally, I am encountering

ERROR Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref at coerceRef (http://localhost:3000/static/js/bundle.js:59386:21) at createChil ...

What is the process for incorporating a collection in Mongoose?

Trying to clear the Users collection before and after tests: before(function(done) { mongoose.connection.collections['users'].drop(function(err) { mongoose.connection.collections['users'].insert(user, done); }); }); after(func ...

Setting the height of columns in a Bootstrap panel to 100%

Is there a way to achieve 100% height for all three columns even without content? Check out this JSFiddle: <div class="row"> <div class="col-md-12"> <div class="shadow panel panel-default"> <div class="blue white-bord ...

React: Struggling to render values within {} of a multidimensional object

I'm facing a challenge that I can't seem to overcome and haven't found a solution for. The values between curly braces are not displaying in the Content and Total components. I've double-checked the JSX rules, but it seems like I might ...

What makes realtime web programming so fascinating?

Working as a web developer, I have successfully created various real-time collaborative services such as a chat platform by utilizing third-party tools like Redis and Pusher. These services offer straightforward APIs that enable me to establish bidirection ...

Protractor functions perfectly on localhost, but encounters a Timeout error when used remotely - the asynchronous callback was not executed within the specified timeout period

Running protractor protractor.conf.js --baseUrl=http://localhost:4200/ executes successfully by filling data, validating elements, etc. However, when attempting to test the same website through a remote URL protractor protractor.conf.js --baseUrl=http://t ...

Incorporating the root element into API blueprint with the utilization of data structures

I've spent hours trying to make this work, pouring over all the documentation. How can I ensure that my array follows the JSON specification by having a root element, using the data structures I've already defined? What adjustments do I need to ...

Excessive geolocation position responses in Angular 5

I am trying to implement an Angular 5 component that will continuously fetch my current location every 3 seconds if it has changed. Here is a snippet of my code: export class WorkComponent implements OnInit { constructor(private userService: UserService ...

Trouble with using .className for form validation

The .className is not applying the formValidation class on getWeight.length < 1 and getHeight.length < 1. I am stuck trying to figure out why this is happening after reviewing the code extensively. Any thoughts on what could be causing this issue? Y ...

Creating a Union Type from a JavaScript Map in Typescript

I am struggling to create a union type based on the keys of a Map. Below is a simple example illustrating what I am attempting to achieve: const myMap = new Map ([ ['one', <IconOne/>], ['two', <IconTwo/>], ['three ...

Incorporate a JSON file into your Swift Playgrounds session

Looking for guidance on how to include a JSON file in a Swift Playground book created for iPad. Can you help me with this process? ...

Transform the object into an array of JSON with specified keys

Here is a sample object: { labels: ["city A", "city B"], data: ["Abc", "Bcd"] }; I am looking to transform the above object into an array of JSON like this: [ { labels: "city A", data: "Abc" }, { labels: "city B", data: "Bcd" }, ]; ...

How can you refresh a functional component using a class method when the props are updated?

I've created a validator class for <input> elements with private variables error, showMessage, and methods validate and isOk. The goal is to be able to call the isOk function from anywhere. To achieve this, I designed a custom functional compone ...

The tabbing feature in bxslider disrupts the alignment of slides, making it

After encountering accessibility issues, I upgraded the bxslider library to version 4.2.3 for better support. Check out this example of bxslider where you can easily tab through the controls: http://jsfiddle.net/qax7w8vt/2/embedded/result/ The problem a ...

Parsing JSON in PHP without allowing duplicate values

Hey guys, I'm facing an issue that is not a duplicate. My json data starts like this: [ { } ] There's no root element in it. Being new to PHP, I am unsure how to parse this data based on the answers I found. Right now, I am working on devel ...

Implementing dotenv in a Node JS package

I'm in the process of developing a Node application that retrieves search results through a Google Custom Search Engine (CSE). To streamline the process, I plan to extract the component responsible for sending requests to Google and receiving the res ...

The range filter is exclusive to the initial controller

My range filter (see code below) is only working on my first controller. I have added the same filter to other controllers in the app.js and HTML, but it's not functioning for some reason. I checked the console for errors, but there are none. Here i ...

My attempts to load the .mtl and .obj files using THREE.js have been unsuccessful

I've been working on creating a 3D model viewer using three.js, but I'm encountering issues with loading .mtl and .obj files. Despite following a tutorial at , the only model that loads successfully is the female one. Here is the code snippet I ...

Is the parameter retrieval method correct or erroneous?

I am looking to retrieve data by clicking a link. Here are the links available: <a class="note" id="' . $data["p_id"] . '" value="1" href="javascript:void(0)">+1</a> <a class="note" id="' . $data["p_id"] . '" value="-1" ...

Showing navigation items in Vuejs based on authentication status

In my current project, I am developing a Single Page Application (SPA) using vuejs with vuetify and integrating authentication via a laravel/passport API. The challenge I'm facing is related to conditional rendering of navigation icons based on user a ...