Is it possible for angular directives to invoke themselves?

I've received some JSON data in the following format:

{
  "menus" : [
    {"name" : "Item 1", "children" : [
      {"name" : "Item 1.1", "url" : "http://www.website.com1/1"},
      {"name" : "Item 1.2", "url" : "http://www.website.com1/2"},
      {"name" : "Item 1.3", "children": [
        {"name" : "Item 1.3.1", "url" : "http://www.website.com1/3/1"},
        {"name" : "Item 1.3.2", "url" : "http://www.website.com1/3/2"},
        {"name" : "Item 1.3.3", "url" : "http://www.website.com1/3/3"}
      ]}
    ]},
    {"name" : "Item 2", "children": [
      {"name" : "Item 2.1", "url" : "http://www.website.com2/1"},
      {"name" : "Item 2.2", "url" : "http://www.website.com2/2"},
      {"name" : "Item 2.3", "url" : "http://www.website.com2/3"}
    ]},
    {"name" : "Item 3", "url" : "http://www.website.com3"}
  ]
}

To create a menu tree structure that mirrors the JSON, I decided to develop a directive for it:

app.directive('menuItem',
function(){
    return {
        restrict : "E",
        scope: { data : '='},
        replace:true,
        templateUrl: 'directives/menu-item.html'
    };  
});

When implemented in the HTML using the directive, it functions correctly for the initial layer:

<menu-item data="menu.data.menus"></menu-item>

The goal is to have the directive generate new nodes if the model being used has a 'children' property, utilizing the same template:

<ul class="menu-items" ng-repeat="item in data">
    <li class="menu-item">
        <div>{{item.name}}</div>
        <div ng-if="item.children.length">
            <menu-item data="item.children"></menu-item>
        </div>
    </li>
</ul>

An error message pops up stating:

Error: [$rootScope:inprog] http://errors.angularjs.org/1.3.0-beta.13/$rootScope/inprog?p0=%24digest

The question remains on how to achieve this desired functionality and gain a better understanding of what's happening.

Fiddle will be shared soon...

Answer №1

Thank you for your help. It turns out that the issue I was experiencing is the same one discussed in How to handle recursive rendering of data using AngularJS

In this specific scenario, it is crucial to note that the template must utilize "ng-init" in order to properly handle recursion.

<ul class="menu-items" ng-repeat="item in data">
    <li class="menu-item">
        <div>{{item.name}}</div>
        <div ng-include="'directives/menu-item.html'" ng-init="data = item.children" class="submenu-item"></div>
    </li>
</ul>

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

Exploring the Positives and Negatives of Using JQuery and Glow JavaScript Libraries

Is there a detailed analysis available that compares JQuery with the BBC's Glow JavaScript libraries? ...

How do we integrate angular-sweetalert with browserify: installation, requirement, and injection?

I recently added angular-sweetalert ^1.1.2 to my project using the command npm install --save angular-sweetalert. However, when I attempted to inject it into my code: var app = angular.module('myApp', [ require('angular-sweetalert') ...

Populate Django Form dropdown with options

Within my form in Django models.py, I have created several fields, one of which is: res_person_1 = models.TextField(verbose_name="Odgovorna osoba 1") The corresponding HTML page structure is as follows: {% extends "blog/base.html" %} { ...

Using ES6 syntax to pass arguments to a React component

I'm currently working on building a sortable list using the react.js library known as "react-sortable-hoc" (https://github.com/clauderic/react-sortable-hoc). Within my "SortableList" component, I've implemented a mapping function on each element ...

Steps for fixing the error "Fixing the MongooseServerSelectionError: Incorrect message size while trying to connect to MongoDB

Encountering a problem when attempting to link up with my MongoDB database using Mongoose in a Node.js program. The error message reads: Cannot connect to the database MongooseServerSelectionError: Invalid message size: 1347703880, maximum allowed: 67108 ...

Error 13 - Permission denied: Apache2 lacks the necessary permissions to write to the file in Flask Python

Before we dive in I recently created a web application using Flask. The main idea is to retrieve the IP address whenever someone visits the website. While everything works perfectly on my Windows machine, I encountered some issues when I moved the project ...

It is my goal to populate the array with numbers while avoiding any duplicate entries

I am currently facing an issue with my code as it is returning a length of 0 instead of the expected result of 5 after excluding duplicates from the array. I have a feeling that there might be something missing in my code, but I just can't seem to fig ...

Google Chrome Android app cannot effectively validate Regx, while it functions seamlessly on Chrome Browser for PCs

I have implemented a Regex validation to allow only alphabetic characters (text only values) in a text field. The validation works perfectly on a PC, but when accessed through an Android device using the Chrome app, it seems like the validation is not effe ...

Adding up the quantities of elements in an array

I am seeking assistance in automatically calculating the sums of objects retrieved each time I click a button to fetch data. However, I am unsure about how to proceed with this task. Below is the script responsible for fetching the data every time the but ...

Using ASP MVC URL Action in JavaScript for dynamic URL generation

I have this on my Razor page Index.cshtml @for (int i = 0; i < Model.Count(); i++) { var cars = Model.ElementAt(i); <a href="@Url.Action("Cars","Home", new { id = cars.Id })"> } Now, I am looking to achieve the same functionality using jQ ...

I need to extract information from the database and save all entries from the form in order to send them to myself. This includes calculating the real-time multiplication of weight and pieces

For a project, I need to gather contact data from the client, and then populate a MySQL database with the information to create new rows in a table. There's an additional requirement where I have to calculate the total weight of element pieces multip ...

Having trouble with Node.js Async/Await not returning as anticipated

Attempting to create a basic report server using node express, but encountering unexpected issues. Below is the API endpoint for generating a report: router.post('/test', async function (req, res) { return res.json(await reportService.test()); ...

Searching for the best way to patiently wait for an animation to finish in angular.js

I have implemented animate.css for animations on my website, but I am facing an issue where I want a specific animation to trigger immediately after another one has completed. Here is the CSS code snippet: .pageRenderer.ng-enter{ animation: fadeIn 1s ...

Enhance the FPS of your three.js application by optimizing performance through CanvasRenderer

I have a tube shape made up of 18738 points stored in a JSON file. The tube is constructed using 2000 points (considering every 9th point). It is comprised of 2000 segments (a requirement), each segment has 12 faces with individual colors applied to them. ...

Obtaining data from a database using json_encode via ajax

Recently, I encountered an issue while using AJAX to fetch data from a database. I decided to use an alert(valData) in the success function to test the data, but unfortunately, nothing was returned from the AJAX call. Curiously, the SQL query I tested dire ...

Using AngularJS to retrieve data with an $http request by its unique

I am currently using AngularJS version 1.6.3 My objective is to retrieve data by id, however, I am facing issues on the AngularJS side. On the server side : app.get("/user/:id", function(req,res){ testDb.findOne({_id : req.params.id}, function(err, ...

Easily convert grams to kilograms with just a click of a button using JavaScript

Enter Grams(g): <input type="text" name="grams" id="grams"><br> <br> <button type="button" onclick="kiloConversion()">Convert to Kilogram</button> <p id="conversionResult"></p> ...

Unable to close Bootstrap 5 modal

All of my modal forms are functioning properly, except for one that I migrated from Bootstrap 4 to Bootstrap 5. This particular modal refuses to close. Neither the Close button (the X at the top of the popup) nor the Cancel button will close the modal. I ...

Tips for triggering a function when the range slider is adjusted

I'm looking to trigger a function whenever a user changes a range slider in my Vue.js project, and I also need to pass the new value to that function. The code snippet below shows what I have so far. <div cla ...

Utilizing variable insertion within HTML tags in Nodemailer: A brief guide

How can a variable be added to an HTML tag in Nodemailer without using HTML templates? var my = "my var"; let transporter = nodemailer.createTransport({ host: "mailer", port: 587, secure: false, auth: { user: 'user', ...