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

React beautiful dnd and Material UI list encountering compatibility problem

I recently encountered an issue while using react beautiful dnd to create a rearrangeable Material UI List. Everything was working correctly, except for the ListItemSecondaryAction within the list. When dragging a list item, the ListItemText and ListItemIc ...

Creating pages or tabs within a table using HTML5 and Angular is a simple and effective way to organize

I have a REST response that returns around 500 records. These records are being displayed in an Angular table. I would like to add customization options for the user, allowing them to choose to display 10/20/30... records per page. Additionally, I want to ...

The functionality of Angular services is not available for use in Jasmine tests

As someone who is relatively new to Jasmine Testing and the Angular framework, I find myself in a unique situation. I am currently struggling with referencing my service functions in my Jasmine tests. Here is a snippet of my Angular Service Initialization ...

How to automatically open JQuery Accordion panels when the page loads

My Accordion loads with the 1st panel open upon page load, but I am looking for a way to have the entire Accordion closed by default. Any help or suggestions on how to achieve this would be highly appreciated. Thank you for your assistance. FIDDLE http:// ...

How can we stop self shadowed faces from being illuminated?

Currently, I am working on creating a city scene in Three.js and experimenting with lighting and shadows. Specifically, I am focusing on a single building that was modeled in 3DS Max, then exported to OBJ format, and converted using a Python converter thro ...

Converting a string to null with PHP's json_encode

I'm currently troubleshooting a problem with a PHP script I've been working on. The script utilizes the phpseclib library to encrypt a password using a public RSA key provided by an ASP.NET application. Everything appears to be functioning proper ...

Navigating between different pages within a website or application using Her

I'm currently working on an Angular front end website using the Yoeman Angular package and hosting it on Heroku with the Node.js build pack. Heroku is able to build the project without any errors, running Gulp and Bower to install dependencies. Howev ...

Is it possible for a hybrid app using Angular 7/1.x to enable Hot Module Replacement (H

Having trouble implementing HMR on a hybrid Angular application using the downgradeModule strategy. I previously sought help from a similar question on Stack Overflow Can an Angular 5/1.x hybrid app support HMR? but didn't find a satisfactory answer. ...

Function in controller making an Ajax request

As a beginner in AngularJS, I am looking to implement a controller with a save function that makes an ajax call. This is how my current code looks: var app = angular.module("myApp1", []); app.controller("AddController", ['$scope', $http { ...

"Keep a new tab open at all times, even when submitting a form in

I have a form with two submit buttons - one to open the page in a new tab (preview) and another for regular form submission (publish). The issues I am facing are: When I click the preview button to open in a new tab, if I then click the publish button a ...

Using AngularJS for posting data without specifying a default value input may lead to unexpected results

I'm curious about why the input is not working when a default value is assigned to the controller and then posted as undefined on the server side. However, if you type directly into the input, it works fine and the value is captured. What's the d ...

What happens when dynamically loaded static resources are loaded?

Currently, I am dynamically injecting HTML into a page using JQuery AJAX. The injected HTML contains script and link tags for JS and CSS files respectively. The issue I am facing is that my initPage() function runs before the script containing its definiti ...

Utilizing Jquery to enhance slide image transitions with navigational links

As a newcomer to jQuery, I am attempting to create a slider using jQuery. Here is the script I have so far: $(function() { var bgCounter = 0, text = [ 'some html code here', 'some html code here', 'some ...

What is the best way to differentiate between a JSON object and a Waterline model instance?

Note: I have posted an issue regarding this on the Waterline repo, but unfortunately, I have not received a simpler solution than my current workaround. Within my User model, along with default attributes such as createdDate and modifiedDate, I also have ...

The change() function in jQuery appears to have a glitch where it does not properly execute during the initial onclick event, but functions correctly for

Here is the button code snippet: <li class="cnt-li"> <button class="btn-container" title="Add Container" data-toggle="modal" data-target=".add-ctn-modal"> <img src="images/add.png" alt="Add Container"> </button> </li> ...

Error encountered while attempting to convert CSV file: InvalidStateError

I've implemented a JavaScript function to be triggered by the 'onclick' event of an HTML button: function exportReportData2() { if ($("#Report").val() != "") { var screenParametersList = buildScreenParameters(); var ...

Wrapping an anchor tag with a div in Codeigniter

Can a div tag be used inside an anchor function? I have a div with the following CSS: #first{ opacity:0; } Now, I want to include it in my anchor element. Here is the code snippet: <?php if(is_array($databuku)){ echo '<ol>&l ...

Journey Swiftly Control

I have a question. Is it possible to manipulate routes in Express? Can I assign multiple routes to the same get or post request when providing an address? module.exports = function (app) { var controller = app.controllers.maps.cliente; app.route(&apos ...

Validating group radio buttons that have been checked

I possess: <div class="group"> <input type="radio" name="myradio" value="1">a <input type="radio" name="myradio" value="2">b </div> <div class="group"> <input type="radio" name="two" value="3">a <input ty ...

What is the best way to style the currently selected option element in a select dropdown?

I am trying to change the font color of specific option elements within a select dropdown by adding style="color: #D4D4D4". When I apply this style directly to an option element like <option value="TEST" style="color: #D4D4D4">TEST</option>, it ...