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

Instead of printing only the JSON data using "response.data", the entire response is being printed out

I'm making a GET request from an AngularJS 1.5x client to a Java HTTP method. In the client, I want to display the response that includes some JSON data. // This is a method from an Angular service that sends AJAX requests this.getTask = function(tas ...

Unexpected behavior observed in JavaScript and AJAX functionality

In my web development project, I've decided to incorporate JavaScript and AJAX for the signup form functionality. However, I seem to be facing some challenges as I try to post all the textbox values from the signup form through AJAX. The code snippe ...

Remove quotation marks from numbers in JSON Builder

I am facing an issue while running the groovy scripts below to create a JSON template. The problem lies in the fact that the integer values in the template are displayed within quotes, treating them as strings. cat port.txt 1001 Below is the JSON builder ...

What is the process for adding a custom header when making an ajax call in a datatable?

Currently, I am utilizing datatables and need to include a custom header for specific server-side requirements. Can anyone provide guidance on how to send a custom header when navigating to the next or previous pages using jQuery datatables? Additional ...

React - optimize performance by preventing unnecessary re-renders of an object property

In my current project, I am working with an auction object that has two properties: remainingTime and amount. To enhance user experience, I integrated a countdown timer using the react-countdown-now library to display the remainingTime. Additionally, there ...

What causes the modal to appear and then vanish suddenly?

I've created a simple modal code with minimal JS involved. When the button is clicked, the modal appears briefly, then the page refreshes and the modal disappears. I'm not sure what could be causing this issue. Any help would be appreciated! h ...

Managing PHP multiple follow-up options in HTML select fields

My goal is to design a form that includes multiple follow-up select fields. These fields will be populated from an array with 3 elements: ID, Name, and followingID. The followingID corresponds to an ID in the array, helping us determine the hierarchical la ...

Error encountered in vue.js due to a ReferenceError when the resize event is used

I'm having trouble obtaining the window height when resizing, and I keep encountering the error ReferenceError: calcOfSliderHeight is not defined. Can someone explain what's happening? Here is my code: let example = new Vue({ el: '#exam ...

Searching for items in a list using SwiftUI with data imported from a JSON

My current SearchView functionality involves filtering through an array called names. However, I now need to modify it to search through a JSON file. The JSON file has the following structure: struct UcmData: Codable, Identifiable { let id: Int le ...

What is the method for creating an array of strings in VueJS?

In my VueJS and Vuetify project, I am working on creating a modal that allows users to input strings into a text field. What I aim to achieve is adding the inputted string to an array when the user clicks on create button. For example, if I enter 'inp ...

PHP - removing a specific value from a JSON object

My JSON file contains the following data: { "0": { "name": "Test1", "devices": [ { "name": "Test1", "code": "654345", "state": "on" }, { "name": "Tes ...

Unfortunately, my capabilities do not allow me to execute the command 'ng build --configuration production

This is the issue that I am facing and need assistance: Error: src/app/app.component.html:1:1 - error NG8001: 'fuse-progress-bar' is not recognized as a valid element: If 'fuse-progress-bar' is an Angular component, please ensure that ...

Pass information to a PHP file using JavaScript when the form is submitted

Essentially, I am looking to extract values from various inputs and spans using JavaScript when the submit input is clicked. These values will then be sent to PHP using $post in order to ultimately send them via email. Previously, I tested replacing all of ...

Enable Parse5's case sensitivity

Recently, I've attempted to parse Angular Templates into AST using the powerful parse5 library. It seemed like the perfect solution, until I encountered an issue - while parsing HTML, it appears that the library transforms everything to lowercase. Fo ...

Tips for converting a JSON string into a table format with jq

Just getting started with Bash scripting and recently discovered jq for JSON manipulation. I'm trying to convert a JSON string into a table format suitable for displaying in the terminal. [{ "name": "George", "id" ...

Steps to sending a request with a custom user agent

In my Angular app, I have successfully implemented server-side pre-rendering with the condition that it will only pre-render if a search bot is sending the request. Now, I need to verify if everything is pre-rendered correctly. However, when I visit my w ...

How can we determine the number of duplicate elements in an array?

Is there a way to tally the occurrences of specific words from a list within a given set of phrases and store the count in designated variables? let counter = []; let wordToCount = ["tomato","cat"]; let phrasesToCheck = ['my cat like potatoes', ...

Executing multiple paths with a single curl request

I am seeking a more efficient way to execute this code. I can currently execute both path blocks with two curl requests, but I would like to find a method of executing both path blocks with a single curl request or perhaps redirect from the first path st ...

Troubleshooting CSS Hover Not Displaying Properly in Angular 14

In the footer class of my HTML, there is a code snippet with chevrons: <div class="link-list"> <div *ngFor="let link of insideLinksLeft | originalOrderKeyValue" class="link"> <a [href]="link.val ...

error : failed to establish a connection to the MongoDB database

Ensure that the first parameter passed to mongoose.connect() or mongoose.createConnection() is a string. MongooseError: The uri parameter for openUri() must be a string, but it was "undefined". Double check that the initial parameter for mongoose.connect() ...