Creating a hierarchical tree structure in AngularJS by recursively traversing JSON data

I am having trouble creating a node tree from a JSON file.

My index.html file should load the node tree recursively from person.json, but I'm stuck in an infinite loop. Can someone please assist me with this?

app.js

(function() {
  var app = angular.module("app", ['directive.cusTree', 'directive.cnode']);
  app.controller("Contrl", function($scope, $http) {
    $scope.some = function() {
      return $http.get('person.json').success(function(data) {
        $scope.nodetree = data;
        return data;
      });
    }
  });
})();

person.json

{
  "person": [{
      "id": 1,
      "name": "A1" ,
      "child": [{
        "id": 1.1,
        "name": "A11",
        "child": [{
          "id": 1.11,
          "name": "A111"
        }, {
          "id": 1.12,
          "name": "A112"
        }, {
          "id": 1.13,
          "name": "A113"
        }]
      }, {
        "id": 1.2,
        "name": "A12"
      }, {
        "id": 1.3,
        "name": "A13",
        "child": [{
          "id": 1.31,
          "name": "A131"
        }, {
          "id": 1.32,
          "name": "A132"
        }, {
          "id": 1.33,
          "name": "A133"
        }]
      }]
    }, {
      "id": 2,
      "name": "B2" 
    }, {
      "id": 3,
      "name": "C3" 
    }, {
      "id": 4,
      "name": "D4" 
    }



  ]
}

item.html

<div ng-click="show(show)" ng-init="show=true" class="container" ng-repeat="node in nodedata" ng-if="nodedata.length>0">
  <ul>
    {{node.name}}
    <br>
    <div ng-if="node.child.length>0">
        <custree nodedata="node.child"> </custree>
    </div>
  </ul>
</div>

index.html

<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
  <script src="app.js" type="text/javascript"></script>
  <script src="cusTree.js" type="text/javascript"></script>
   <script src="cnode.js" type="text/javascript"></script>

</head>

<body>

  <div ng-controller="Contrl as n">


    <div ng-init="nodetree=some()">
      <div ng-repeat="node in nodetree">



          <div class="container">

         <custree nodedata="node"> </custree>

        </div>
          <br>
      </div>

    </div>

  </div>

</body>

</html>

cusTree.js

angular.module('directive.cusTree',[])
.directive('custree',function(){

return{
  restrict :'E',
  scope: {

    nodedata:'='

  },
  templateUrl:"item.html",
  controller:function($scope){
//console.log("new="+ JSON.stringify($scope.nodedata));


  }

};




});

Answer №1

If you want to create a tree using AngularJS, you need to define 2 directives as shown below:

app.directive('nodeTree', function () {
  return {
    template: '<node ng-repeat="node in tree"></node>',
    replace: true,
    restrict: 'E',
    scope: {
      tree: '=children'
    }
  };
});
app.directive('node', function ($compile) {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: 'partials/node.html', // HTML for a single node.
    link: function (scope, element) {
      /*
       * Here we check if the current node has children and compile/render them.
       * */
      if (scope.node && scope.node.children && scope.node.children.length > 0) {
        var childNode = $compile('<ul class="tree" ng-if="!node.visibility"><node-tree children="node.children"></node-tree></ul>')(scope);
        element.append(childNode);
      }
    },
    controller: ["$scope", function ($scope) {
      // Function to toggle the visibility of children
      $scope.toggleVisibility = function (node) {
        node.visibility = !node.visibility;
      };
      // Function to mark check/uncheck all nodes
      $scope.checkNode = function (node) {
        node.checked = !node.checked;
        function checkChildren(c) {
          angular.forEach(c.children, function (c) {
            c.checked = node.checked;
            checkChildren(c);
          });
        }
        checkChildren(node);
      };
    }]
  };
});

For more information, you can visit this Github Link which includes a working demo.

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

What is the process for generating a submatch for this specific expression?

Trying to extract account status information using a regular expression in the DOM. Here is the specific string from the page: <h3>Status</h3><p>Completed</p> Current regular expression being used: <h3>Status</h3>[&bs ...

An unexpected error occurs when attempting to invoke the arrow function of a child class within an abstract parent class in Typescript

Here is a snippet of code that I'm working on. In my child class, I need to use an arrow function called hello(). When I try calling the.greeting() in the parent class constructor, I encounter an error: index.ts:29 Uncaught TypeError: this.hello is ...

What is the correct way to use setInterval in a React component's constructor?

I'm trying to set an interval when the main component renders. I attempted to do this in the constructor like so: constructor(props) { super(props); this.props.fetchUserInfo(); this.props.fetchProducts(); setInterval(console.log(&a ...

Utilizing @casl/vue in conjunction with pinia: A guide to integrating these

I'm currently facing an issue with integrating @casl/ability and Vue 3 with Pinia. I'm unsure of how to make it work seamlessly. Here is a snippet from my app.js: import { createApp } from "vue" const app = createApp({}) // pinetree i ...

How to retrieve a MySQL column in Node.js using template literals

I have been trying to retrieve a field from MySQL in my Node.js file using template literals, but I am struggling to get the value. In my post.controller.js file, you can see where it says message: Post ${body.post_id} was successfully created, with post_i ...

Extracting POST information through PHP's AJAX Request

I am facing an issue where I keep receiving null values when using the following code: Here is my Ajax request: formData = { u: "3959eeadb32e02b85a792e21c", id: "6d7613df26" }; $.ajax({ ...

What is the best way to populate nested elements with jQuery?

I am trying to showcase the latest NEWS headlines on my website by populating them using Jquery. Despite writing the necessary code, I am facing an issue where nothing appears on the webpage. Below is the HTML code snippet: <div class="col-md-4"> ...

Is there a way to toast the values of an array retrieved from a getter within my object?

My data in the format of a JSON Array looks like this and I am attempting to display the user_review_ids values - 63,59,62 using a toast message. However, instead of getting the actual values, I keep receiving what seems to be a reference to them, such as ...

Can a WCF service utilize both the SOAP and JSON methods simultaneously?

I recently started working with WCF, and I need to utilize the same WCF for bothSOAPandJSON` formats using the post method. Is this achievable? Any guidance would be greatly appreciated. ...

The variable req.body.Dates has not been declared

I am currently working on a project that involves dynamically populating two drop down menus using SQL Server. Depending on the selected items, I need to load a specific ejs template using AJAX. My goal is to load data based on the selected criteria. For e ...

Combining and removing identical values in JavaScript

I need to sum the price values for duplicated elements in an array. Here is the current array: var products = [["product_1", 6, "hamburger"],["product_2", 10, "cola"],["product_2", 7, "cola"], ["product1", 4, "hamburger"]] This is what I am aiming for: ...

Retrieving data in JSON format from the server

Could someone please assist me with this? I am facing a dilemma with a PHP script that returns a JSON response labeled as "success" when a condition is met. Although, the log statement shows the response as "success", it fails to be recognized within an if ...

Update the div element without needing to reload the entire page

Is there a way to reload a div tag without refreshing the entire page? I understand this question has been asked before, but I want to make sure I have a clear understanding. <p>click HERE</p> <div class="sample"> <?php functi ...

Creating a layered image by drawing a shape over a photo in Ionic using canvas

While there are plenty of examples demonstrating how to draw on a canvas, my specific problem involves loading a photo into memory, adding a shape to exact coordinates over the photo, and then drawing/scaling the photo onto a canvas. I'm unsure of whe ...

Contact form repair completed - Messages successfully delivered

I am facing an issue with the contact form on my HTML landing page. Currently, when you click the 'Submit' button, it redirects to a new PHP page displaying 'Success'. Is there a way to make it so that upon clicking 'Submit' a ...

What is the best way to eliminate the additional square bracket from a JSON file containing multiple arrays?

Seeking JSON data from an array, I encountered an issue with an extra square bracket appearing in the output. After attempting $episode[0] = $podcast->getPodcastByCategoryId($id);, only partial data was retrieved, corresponding to the first iteration. ...

Is ng-repeat failing to bind values in the Dom?

When loading data dynamically to ng-repeat, I am encountering an issue where the data is not binding to ul. Typically, this can happen with duplicate indexes, but in my case I'm unsure of what's causing it. Any suggestions? main.html <div> ...

Experiencing problems with npm and bower installations, along with deprecated modules while setting up angular-phonecat project

Trying to execute npm install in terminal while setting up angular-phonecat based on instructions from https://docs.angularjs.org/tutorial Encountering issues with deprecated modules and errors during the bower install phase. Seeking advice on how to upd ...

Set the Vue 3 Select-Option to automatically select the first option as the default choice

I am attempting to set the first select option as the default, so it shows up immediately when the page loads. I initially thought I could use something simple like index === 0 with v-bind:selected since it is a boolean attribute to select the first option ...

Attempting to use Selenium in JavaScript to download a file with a new element called 'TransitionRejection'

I am looking to streamline the process of downloading multiple files from a website. To achieve this, I navigate through several pages to obtain the file IDs using selenium and a perl script. Since selenium does not have a built-in download function and u ...