Custom AngularJS menu directive using a JSON file to generate submenus

As a newcomer to angularJs, I am looking to create a dynamic menu with submenus using a .json file. It's important for me to be able to easily add new menus and submenus through the same .json document.

<a href="#" ng-repeat="item in menuHeader">{{item.NAV.menu[x].subItens[x].nome}} </a>

I believe this code snippet allows me to access elements within other elements, which is essential since I have multiple submenus and menus in mind. I initially attempted to use a For loop within the HTML template, but encountered some challenges. Can anyone offer guidance on how to resolve this issue or suggest an alternative approach?

Check out the demo here: CLICK HERE!

Thank you for your help!

Answer №1

Give this a try, I believe it will meet your expectations :

var app = angular.module('myApp', []);

function Ctrl($scope) {
    var data = [
    {
        "NAV": {
            "menu": [

                {
                    "id": 0,
                    "nome": "Menu 1",
                    "subItens": [
                        {
                            "id": 0,
                            "nome": "SUB MENU 1"
                        },

                        {
                            "id": 1,
                            "nome": "SUB MENU 2"
                        },

                        {
                            "id": 2,
                            "nome": "SUB MENU 3"
                        }
                    ]
                },

                {
                    "id": 1,
                    "nome": "Menu 2",
                    "subItens": [
                        {
                            "id": 0,
                            "nome": "SUB MENU 1_2"
                        },
                        {
                            "id": 1,
                            "nome": "SUB MENU 2_2"
                        }
                    ]
                },

                {
                    "id": 2,
                    "nome": "Menu 3",
                    "subItens": [
                        {
                            "id": 0,
                            "nome": "SUB MENU 1_3"
                        }
                    ]
                }

            ]
        }
    }];

    $scope.menuLinks = data[0].NAV.menu;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Ctrl">
                    <ul class="nav">
                        <li ng-repeat="link in menuLinks"><a href="{{link.url}}" class="{{link.sub && 'dropdown-toggle' || ''}}" data-toggle="{{link.sub && 'dropdown' || ''}}">{{link.nome}}
                        </a>
                            <ul class="dropdown-menu" ng-show="link.subItens">
                                <li ng-repeat="subItem in link.subItens"> <a href="#123">{{subItem.nome}}</a>
                                </li>
                            </ul>
                        </li>
                    </ul>
</div>

Answer №2

Issue Resolved!

After making a simple adjustment to this part:

<a href="#" onclick="updateSub($index)">

and modifying the following condition:

show-if="$index == currentID">

The $index now correctly retrieves the local array. =)

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

Ajax is incapable of achieving success or encountering failure

I'm having some trouble displaying search results on the view using AJAX. The action retrieves JSON data and sends it, but for some reason the AJAX call is not receiving the data. $(function () { $("#btnSearchForUser").click(function () { ...

Endless Loop: AngularJS app.run() Promise caught in infinite cycle

I have a situation in my AngularJS app where I am using app.run() to check if a user is logged in before displaying the site to restrict access to non-registered users. Initially, I faced issues with the isLoggedIn function returning false when reloading t ...

Encountered an error during the production build of NEXTJS, where it panicked due to the global thread pool not being initialized

While hosting my app on Heroku and running git push heroku main, I encountered the following error: panicked at 'the global thread pool has not been initialized.: threadpool builderror { kind: ioerror(error { kind: unsupported, message: "operatio ...

What is the best way to retrieve content from a different website using javascript in an asp.net environment?

Currently working on a web application in asp.net where I want to provide users with a JavaScript code that allows them to fetch content from my website and display it on their own website. To handle user requests on my website, I have implemented a gener ...

Step-by-step guide on integrating Bulma page loader extension as a Vue component

Is there a way to integrate the Bulma-extension page-loader element as a Vue component in my project? I attempted to import page-loader.min.js and use it, but unfortunately, it didn't work as expected. <template> <div class="steps"> ...

How to utilize variables in Angular module functions?

My experience with Angular is fairly new, and I recently encountered a debugging issue in my application that unfolded like this: Imagine I am adding a new directive to an existing module defined in another .js file. When I tried using the syntax below: ...

Forms for uploading and submitting multiple files

On my single page, I have several file upload forms that are generated in a loop. The issue is that the first file upload control works fine, but the others do not. <div> <form action="/docs/1046/UploadDocument?Id=1046&amp;propertyTypeId ...

Exploring AngularJS concepts with a focus on understanding view problems (ng-if, ng-switch)

As a beginner diving into the world of AngularJS and JavaScript, I find myself facing a challenge that I hope to get some advice on today. The issue revolves around displaying an input block with or without the "readonly" attribute. To better explain my pr ...

`Need to clean parameters for safe use in JavaScript code?`

I am working with the php code below: <?php $redirect_lp = $_GET['lp']; ?> <script> setTimeout(function(){ window.location.href = "<?php echo $redirect_lp; ?>"; }, 10) </script> How can I properly sanitiz ...

How the React Component Class Executes OnChange Event in a Closure

When working on my React code, I found myself creating a closure by calling "onChange." class CityInput extends React.Component { constructor( props ){ super( props ); this.state = { city : "", country : "" ...

Challenge in backward compatibility when converting from .on() to .live()

Struggling to make hammer.js work with an outdated 1.6 jQuery in my CMS. The function "on()" isn't available, so I have to use "live()". Here are the two instances: 1. var hammertime = new Hammer(element[0], { drag_lock_to_axis: true }); hammertime. ...

Function generator within a component

I have a class-based component and I need to declare a generator function for an API call inside it without using fetch.then. Below is the code snippet: class SearchField extends React.Component { componentWillUnmount() { this.props.clearSearchStat ...

Class variable remains unchanged following AJAX request

Upon completion of the ajax request, two integers are received - this.N and this.M. However, these values are not being set by the storeDims() function even though the correct decoding is done on the dims variable. This implies that I am unable to access ...

When you scroll a fixed element on the page, the block is truncated

I made a modification for adding cart items and included a script for managing my cart The cart is supposed to stick to the right edge and scroll up and down on the page Everything seems to work, but there's a slight issue when I click on Add 1 and ...

Develop a custom autocomplete feature using Formik in React for selecting values from an array of objects

Looking to Add Autocomplete Functionality in Your React Application Using Formik for Seamless Selection of Single and Multiple Values from an Array of Objects? Take a Look at this Code snippet! [see image below] (https://i.stack.imgur.com/ekkAi.png) arra ...

Start the Express server by utilizing Grunt

Can anyone assist me with adding a task to my Gruntfile that will start my Express server instead of the default one? I attempted to create a task and use require("server.js"), but it doesn't seem to be working properly. When I run "grunt mytask", the ...

When implementing 'useGlobalGuards' in NestJS, remember to exclude endpoints for enhanced security

After implementing the useGlobalGuards method in my main.ts file, all endpoints now utilize the AuthGuard. This guard triggers a 401 error if a valid auth token is not present in the request header. Previously, I used @UseGuards(AuthGuard) on individual cl ...

What is the functionality of the save callback in Mongoose?

Currently in the process of learning about Mongoose's save() function for the MEAN stack. This particular function requires a callback as outlined in its API documentation: Model#save([options], [fn]) Saves this document. Parameters: [options] < ...

Is it common for NA values to appear in the data frame due to JSON parsing?

I recently obtained a collection of JSON files from the YELP public data challenge. These files can be found at this link: The files are in NDJSON format, and I have successfully read them using the following code: library(jsonlite) df <- stream_in(fi ...

Leverage the selected values to dynamically generate a table using jQuery

Can someone help me figure out how to store multiple values from a selection and then create an array using jQuery? Here's the scenario: In my multiple selection, I have 5 values: <select name="animal" id="animal" multiple="multiple">    ...