Display JSON data in a hierarchical tree structure using AngularJS

Looking to display three nodes of a JSON file as a tree using AngularJS. The nodes are data.key, data.parentItem, and data.title.

Below is the JavaScript code:

var phonecatApp = angular.module('myApp', [])
phonecatApp.controller('myController', function myController($scope, $http) {
  $http.get('https://api.zotero.org/users/475425/collections/9KH9TNSJ/items?format=json')
    .then(function (response) {
      var data = response.data

      data = data.filter(function (obj) {
          return true
        })
        .map(function (obj) {
          return {
            key: obj.key,
            parentItem: obj.data.parentItem,
            title: obj.data.title
          }
        })

      var log = []
      var parent = angular.forEach(data, function (value, key) {
        if (value.parentItem === undefined) {
          this.push(value)
        }
      }, log)
      $scope.paR = log

      var nlog = []
      var children = angular.forEach(data, function (value, key) {
        if (value.parentItem !== undefined) {
          this.push(value)
        }
      }, nlog)
      $scope.chilD = nlog
    })
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <title>Hello</title>
  <link href=" css/bootstrap.min.css " type="text/css " rel="stylesheet ">
  <link href="themes/default/style.min.css " type="text/css " rel="stylesheet ">
  <link href="css/angular-json-human.min.css" type="text/css" rel="stylesheet">
</head>

<body ng-controller="myController ">
  <div>
    <ul ng-repeat="myJ in paR">
      <li>
        <h3>{{myJ.key}}</h3></li>
      <li>{{myJ.title}}</li>
    </ul>
    <ul ng-repeat="myN in chilD">
        <li>
          <h3 style="color:red">{{myN.key}}</h3></li>
        <li>{{myN.title}}</li>
      </ul>
  </div>

  <script src="js/angular.min.js "></script>
  <script src="js/jquery-1.12.4.min.js "></script>
  <script src="js/bootstrap.min.js "></script>
  <script src="js/npm.js "></script>
  <script src="js/jstree.min.js "></script>
  <script src="tree.js "></script>
</body>

</html>

My JSON items can either be parents or children. Need assistance on displaying them in a tree format with respect to parent-child hierarchy following the nLogn rule.

Answer №1

If you're looking for an effective directive to use, consider checking out the angular treeview module.

It works with JSON data structured like this:

$scope.treedata = 
[
    { "label" : "User", "id" : "role1", "children" : [
        { "label" : "subUser1", "id" : "role11", "children" : [] },
        { "label" : "subUser2", "id" : "role12", "children" : [
            { "label" : "subUser2-1", "id" : "role121", "children" : [
                { "label" : "subUser2-1-1", "id" : "role1211", "children" : [] },
                { "label" : "subUser2-1-2", "id" : "role1212", "children" : [] }
            ]}
        ]}
    ]},
    { "label" : "Admin", "id" : "role2", "children" : [] },
    { "label" : "Guest", "id" : "role3", "children" : [] }
];   

You can see how it will look when displayed https://i.sstatic.net/IKwbu.png

Just make sure to format your data accordingly before implementing it.

Answer №2

this is the answer !!!!

var phonecatApp = angular.module('myApp', [])
phonecatApp.controller('myController', function myController($scope, $http) {
  $http.get('https://api.zotero.org/users/475425/collections/9KH9TNSJ/items?format=json')
    .then(function(response) {
      var data = response.data

      data = data.filter(function(obj) {
          return true
        })
        .map(function(obj) {
          return {
            key: obj.key,
            parentItem: obj.data.parentItem,
            title: obj.data.title
          }
        })
      console.log(data)

      $scope.getParentData = function() {
        var log = []

        angular.forEach(data, function(value, key) {
          if (value.parentItem === undefined) {
            this.push(value)
          }
        }, log)
        return log
        console.log(log)
      }

      $scope.getChilds = function(p) {
        var log = []

        angular.forEach(data, function(value, key) {
          if (!value.parentItem || value.parentItem !== p.key) {
            return
          }
          this.push(value)
        }, log)
        return log
        console.log(log)
      }
    })
})
<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>
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <title>nested tree</title>
</head>

<body ng-controller="myController" class="container">

  <ul>
    <li ng-repeat="myPar in getParentData()">
      <h4>{{myPar.title}}</h4>
      <ul>
        <li ng-repeat="myChild in getChilds(myPar)">
          <p>{{myChild.title}}</p>
        </li>
      </ul>
    </li>
  </ul>
</body>

</html>

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

Difficulty Sorting Dates in Material UI DataGrid

I have a DataGrid in Material UI, and one of my columns displays dates. Following the guidance from the Material UI documentation, I have set the type to "date" in the column array: { field: "submittedAt", headerName: "Submitted", minWidth: 150, flex: 2, t ...

Encountering an issue such as "Exceeding the maximum number of re-renders. React restricts the amount of renders to avoid

Currently, I am attempting to update the state within the request data method for a string variable as shown below: const ViewChangeRequest = () => { const [requestStageValue, setRequestStage] = useState(''); const { data: request ...

How come Vue.js is not showing the image I uploaded?

Even though I can successfully print the image URL, I'm facing an issue where the img tag is not displaying it, despite my belief that I've bound it correctly. <html> <head> <title>VueJS Split Demo</title> <script t ...

How to associate an object with a component in Angular2/TypeScript using HTTP

I am currently working on displaying a list of item names retrieved from a REST API. By utilizing the map function on the response observable and subscribing to it, I was able to obtain the parsed items object. Now, my challenge is how to bind this object ...

Displaying spinner until the entire section has finished loading

In order to display a loading spinner until all images in a specific section of the page have fully loaded, I am utilizing Django, jQuery, and Ajax technologies. The HTML structure consists of two main divs: On the left side, there is a table, while on t ...

What is the best way to handle constants in TypeScript?

I am facing an issue with a React component I have created: const myComponent = ({constant}: Iprops) => ( <div> {CONSTANTS[constant].property ? <showThis /> : null </div> ) The error message says 'element implicitly has ...

Ajax request in Rails not receiving a response from the controller

After troubleshooting a simple GET request to the controller action, I confirmed that the request is being made successfully and there are no issues with the controller executing the action. However, I am not receiving any response data. $.ajax({ url: ...

When selecting a different file after initially choosing one, the Javascript file upload event will return e.target as null

Currently, I have implemented file uploading using <input>. However, when attempting to change the file after already selecting one, the website crashes and states that event.target is null. <Button label="Upload S3 File"> <input ...

Is it possible to implement a Promise.some() function that includes a timeout

Scenario - collect multiple URLs and cache the responses. URLs that are processed quickly (e.g. within 500ms) are included in the current pass, while those that take longer are still cached for use in the next round (approximately 10 minutes later in our a ...

Using jQuery to Decode the XML Document Containing National Threat Level Data

Recently, I've been experimenting with using jQuery to extract data from the DHS Threat Level found in their XML file. However, despite my efforts, I haven't been able to make it work. As a newcomer to Javascript and non-presentational jQuery, I& ...

How can I pass the dynamically generated ID from PHP to AJAX/jQuery using an anchor tag?

I'm seeking help with jQuery and Ajax as I am new to it. My issue is that I have multiple 'edit' buttons in a table, one for each row's data. When I click on an edit button to modify the data, they all open at once instead of just the s ...

How to display logged-in user information on the homepage

Code for multiuser login $scope.users = [ {uname: 'fida', password: 'fida', age:26, department:"science"}, {uname: 'anu', password: 'anu', age:23,department:"maths"}, {uname: 'nida&apo ...

JavaScript - Sending Form Data with Local Time

I want to automatically submit a form at a specific time of day The form should be submitted every day at "15:30:00" Here is the JavaScript code I have written: <script type="text/javascript> function initClock() { var now = new Date(); var h ...

Using query strings to manipulate the URL of an iframe and add additional information

I am facing a challenge with integrating my legacy perl application into an MVC application. I have set up a structure where the legacy application is loaded into an iframe within default.aspx, but I need to capture the URL of each page within the iframe a ...

The bootstrap switch button remains in a neutral grey color

Ordinary: Initially clicked: Click again: After the second click, it remains grey and only reverts on a different action like mouse click or selection. Is there a way to make it go back to its original state when unselected? ...

What is the best way to gather user input and incorporate it into a selected template, ensuring it is verified before sending?

I'm in the process of developing a project that involves gathering user input through a collector and displaying it on my template for verification before sending it out. The format I'm aiming for can be seen here: This is the template format I ...

Utilizing a CSS identifier with jQuery

I'm struggling with a basic .each statement for comments where I want a form at the bottom to add new comments. The goal is simple - when someone submits a comment, I want it to display just above and move the form down using jQuery. Although this fun ...

Creating a Dataframe in Pandas with a continuous stream of partial dictionary inputs

My task involves handling a stream of packets that are arriving from different sources in the form of synchronized python dictionaries. Each packet has a unique sequence number and varying attributes. {'seq': 1, 'A':0, 'B':2, ...

Browserify is unable to locate the 'jquery' module

While attempting to package my app with browserify, I encountered the following error message: Cannot find module 'jquery' from '/home/test/node_modules/backbone' I have searched for solutions to this issue, but none of them seem to ...

A Guide to Performing Dual API Calls within Angular for a Single Component

Is there a way to make two separate API calls within the same Angular component? For instance, I have an order component that is rendered twice in a tabular manager on a page. Using ngif condition, I display different data for TAB1 and TAB2. The issue is ...