Angular directive used to create a nested tree list

Currently struggling with a nested list Directive in Angular. Whenever I attempt to run the code, the browser crashes due to the recursive call of the directive.

My goal is to display a new list item if the data's children property contains items.

Here is a link to a fiddle of my code where I have removed the directive's self-call to prevent crashing the browser: http://jsfiddle.net/8p3bf4ec/

JS:

var jsonData = {
    "title": "Home",
    "author": "Mary",
    "children": [
        {
            "title": "Clothing",
            "author": "Robert",
            "children": [
                {
                    "title": "Shirts",
                    "author": "Bill",
                    "children": []
                }
            ]
        },
        {
            "name": "Electronics",
            "author": "William",
            "children": []
        }
    ]
};

angular.module('myApp', []);

angular.module('myApp').directive('itemList', function() {
    return {
        scope: true,
        templateUrl: 'itemListTemplate.html',
        controller: function($scope) {
            $scope.nodes = jsonData;
            console.log($scope.nodes);
        }
    };
});

Template:

<div ng-app="myApp">

    <item-list></item-list>

    <script type="text/ng-template" id="itemListTemplate.html">
        <ul>
            <li ng-repeat="node in nodes">
                {{node.title}}
            </li>
        </ul>
        <!-- Removed this because it makes the browser crash
        <item-list></item-list>
        -->
    </script>

</div>

Answer №1

The reason for the issue is that you are recursively navigating through jsonData instead of its children nodes. Perhaps it would be better to avoid using a directive in this case as it unnecessarily complicates things without adding much value. Instead, consider using ng-include as a simpler alternative. Here's an example:

<script type="text/ng-template" id="tree-view">
<ul>
    <li ng-repeat="item in items">
        <!-- display any desired data from the item -->
        <div
            ng-if="item.children && item.children.length"
            ng-init="items=item.children"
            ng-include="'tree-view'">
        </div>
    </li>
</ul>
</script>

<div class="tree-view" ng-include="'tree-view'"></div>

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

IE9 presents a frustrating issue where the jQuery select box value is returning as

I've been battling a bug for over 2 hours now. My javascript code is supposed to generate a two-level select box for tasks and subtasks from JSON data. However, I recently discovered that this code doesn't function properly on IE9, and possibly ...

Verify the fonts that are functioning correctly

Despite using the "dancing script" Google webfont and adding it through @font-face, font-family, I am unable to see it in the browser. I would like to know how to determine which fonts are correctly uploaded and rendering properly while viewing a website ...

Validation check: Ensure that the value does not match any other field

Looking for a method to compare two fields and only validate them if they are not equal. This is the approach I've tried, but it's not working: yup .number() .required() .notOneOf( [FormField.houseHoldMembers as any], &ap ...

Working with Angular to Retrieve a File Using Ajax

My dilemma revolves around a service that is capable of generating a CSV file and sending it back to the page through an http/ajax get request. The desired user interaction involves clicking a button, triggering the service call, and initiating the downloa ...

what can prevent a React component from re-rendering?

Being a novice in the realm of React, I find myself with a perplexing query. Within my application, I have two distinct components - the parent component named Goals and its child, EditGoal. The Goals component functions to display all goals, while the Edi ...

Introducing Exciting Additions in Angular Version 1.2

Recently I started working with AngularJS using version 1.0.5, but now I am considering upgrading to release 1.2. Can someone advise me on the main things I need to consider to ensure my app continues to function properly? If possible, could you also hig ...

Deleting a file in Express.js after it has been downloaded from the local file system

I'm working on an Express handler that is designed to download a file after detecting a valid file path in the directory entries. The handler includes a command-line option to delete the file after it has been successfully downloaded: res.downloa ...

What is the best way to implement a dropdown menu with JavaScript or jQuery?

I'm looking to create a dynamic dropdown list using Javascript or JQuery that mirrors the functionality of selecting countries, states, and cities. Can someone provide guidance on the best code to achieve this? Below is a snippet of my existing code: ...

Tips for maintaining consistent header and footer while developing the front end using JavaScript

Is it possible to maintain the same header and footer on all pages of a website if using JavaScript for the front end and PHP for the back end? While I am comfortable doing this with PHP, I am curious if it can also be achieved with JavaScript or HTML, o ...

Review the Drawer Item's Render Method

I have been using react-native with expo and following a specific guide closely: Is there an alternative way to implement this without the use of icons at the moment? Upon compiling, I encountered an error regarding the Render Method of DrawerItem. I&apo ...

Tips for transferring values between functions within the same scope

Currently, I am facing an issue where I have two functions within the same controller and I am attempting to pass a value from one function to another. Unfortunately, I keep receiving an error that says TypeError: Cannot read property 'activeDataset&a ...

Ways to ensure certain code is executed every time a promise is resolved in Angular.js

Within my Angular.js application, I am executing an asynchronous operation. To ensure a smooth user experience, I cover the application with a modal div before initiating the operation. Once the operation is complete, regardless of its outcome, I need to r ...

How to pass variables in AngularJS

When displaying data in a grid, I need to change the button icon on click of the active or inactive button. The functionality is working well, but I am having trouble finding the clicked active button to change its icon. In jQuery, we can use "this", but ...

What is the best way to combine two arrays and generate a new array that includes only unique values, similar to a Union

Here are two arrays that I have: X = [ { "id": "123a", "month": 5, "markCount": 75 }, { "id": "123b", "month": 6, "markCount": 85 ...

Is there a way for me to store the output of an AJAX call?

One of the challenges I'm facing involves an AJAX request: $.ajax({ url: 'script.php?val1=' + value1 + '&val2=' + value2, dataType: "json", success: function (data) { var newValue1 = data[0]; ...

Revamp the design of the Google image layout

I am trying to replicate the layout of a Google search results page. My goal is to have a full-width div appear on screen when an image is clicked, with a small triangle at the bottom of the clicked image. I attempted to place the img inside another div, ...

Contrast in behavior when utilizing ng-include with webpack on a local environment compared to in a

Currently utilizing webpack alongside angular, I have an HTML file that includes ng-include: <ng-include src="stringUrl" ng-if="true"></ng-include> I've set the stringUrl in the controller: this.$scope.stringUrl = 'app/some-view.h ...

Concatenate data received from PHP to a JavaScript variable and return it

In my current app development project, I have the following code snippet. The variable valdat is sent to a specified URL, processed through a PHP file, and then returned to the app. How can I add the data displayed in the alert message to another variabl ...

OnsenUI: driving engagement with push notifications

Can notifications be sent from the app without relying on 'Push.send()' in the back-end? My app is straightforward - it uses a timer and I need to alert the user when the time expires, even if they are not actively using the app at that particula ...

Is it possible to modify the CSS injected by an Angular Directive?

Is there a way to override the CSS generated by an Angular directive? Take, for instance, when we apply the sort directive to the material data table. This can result in issues like altering the layout of the column header. Attempting to override the CSS ...