Looking to display a JSON-based menu using AngularJS?

Having trouble displaying a dropdown menu when trying to print a menu from a JSON file.

https://i.sstatic.net/fNLxw.png

JSON Data

[{
    "Option": "Request",
    "Name": "<a href=\"#/request\"><i class=\"material-icons left\">flight</i>Request</a> ",
    "Description": "Form for Request",
    "Submenu": []
}, {
    "Option": "Queries",
    "Name": "<a href=\"#/queries\"><i class=\"material-icons left\">search</i>Queries</a> ",
    "Description": "Form for Queries",
    "Submenu": []
}, {
    "Option": "Transfer",
    "Name": "<a href=\"#/transfer\"><i class=\"material-icons left\">attach_money</i>Transfer</a> ",
    "Description": "Transfer",
    "Submenu": []
}, {
    "Option": "Administration",
    "Name": "<a class=\"dropdown-button\" data-activates=\"administration\"><i class=\"material-icons left\">settings</i>Administration<i class=\"material-icons right\">arrow_drop_down</i></a> ",
    "Description": "Administration Menu",
    "Submenu": [{
        "Option": "Reservations",
        "Name": "#/reservations ",
        "Description": "Reservations",
        "Submenu": null
    }, {
        "Option": "Global",
        "Name": "#/global ",
        "Description": "Global",
        "Submenu": null
    }, {
        "Option": "Conventions",
        "Name": "#/conventions ",
        "Description": "Conventions",
        "Submenu": null
    }, {
        "Option": "Application",
        "Name": "#/application ",
        "Description": "Application",
        "Submenu": null
    }]
}]

HTML Code:

<li ng-repeat="item in menu" ng-bind-html="item.Name" ng-hide="!authentication.isAuth">
   <ul ng-if="item.Submenu.length>0" id="administration" class="dropdown-content">
      <li ng-repeat="items in item.Submenu"><a href="#/reservations">Reservations</a></li>
      <li><a href="#/reservations">Reservations</a></li>
      <li><a href="#/global">Global</a></li>
      <li><a href="#/conventions">Conventions</a></li>
      <li><a href="#/application">Applications</a></li>
   </ul>
</li>

Currently using angularjs 1.3.16 and frontend materializecss for the project.

Answer №1

Here is the solution for your question:

<li ng-repeat="item in menu" ng-hide="!authentication.isAuth" class="{{item.Submenu.length ? 'dropdown-button' : ''}}" data-activates="{{item.Submenu.length ? 'administracion' : ''}}">
    <span ng-bind-html="item.Nombre"></span>
    <ul ng-if="item.Submenu.length>0" id="administracion" class="dropdown-content">
      <li ng-repeat="subItem in item.Submenu"><a ng-href="{{subItem.Nombre}}" ng-bind-html="subItem.Descripcion"></a></li>
    </ul>
</li>

To make the submenu work with Materialize CSS, follow these steps:

  • Include jQuery: Navbar dropdowns require jQuery.
  • Include Materialize minified JavaScript
  • Apply classes correctly: The item that triggers the dropdown should have the class dropdown-button. The ul with submenu items should have the class dropdown-content and a unique id
  • The element with dropdown-button class must have the data-activates attribute set to the id of the ul containing the submenu items

Lastly, add this code snippet to activate the dropdowns:

$(document).ready(function() {
  $(".dropdown-button").dropdown();     
});

For Angular apps, consider using Angular Material over Materialize CSS.

Here is a functional snippet without using ng-bind-html:

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

  exampleApp.controller('Controller', ['$scope', function ($scope){
    $scope.menu = [ {
        "Option": "Request",
        "Name": "<a href=\"#/request\"><i class=\"material-icons left\">flight</i>Request</a> ",
        "Description": "Request Form",
        "Submenu": []
        }, {
        "Option": "Queries",
        "Name": "<a href=\"#/queries\"><i class=\"material-icons left\">search</i>Queries</a> ",
        "Description": "Queries Form",
        "Submenu": []
        }, {
        "Option": "Transfer",
        "Name": "<a href=\"#/transfer\"><i class=\"material-icons left\">attach_money</i>Transfer</a> ",
        "Description": "Transfer",
        "Submenu": []
        }, {
        "Option": "Administration",
        "Name": "<a class=\"dropdown-button\" data-activates=\"administration\"><i class=\"material-icons left\">settings</i>Administration<i class=\"material-icons right\">arrow_drop_down</i></a> ",
        "Description": "Administration Menu",
        "Submenu": [{
            "Option": "Reservations",
            "Name": "#/reservations ",
            "Description": "Reservations",
            "Submenu": null
        }, {
            "Option": "Globals",
            "Name": "#/globals ",
            "Description": "Globals",
            "Submenu": null
        }, {
            "Option": "Agreements",
            "Name": "#/agreements ",
            "Description": "Agreements",
            "Submenu": null
        }, {
            "Option": "Application",
            "Name": "#/application ",
            "Description": "Application",
            "Submenu": null
        }]
        }];
}]);

$(document).ready(function() {
  $(".dropdown-button").dropdown();     
});
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-sanitize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"></script>
<nav>
<div ng-app="app" ng-controller="Controller" class="nav-wrapper">
  <ul>
    <li ng-repeat="item in menu" class="{{item.Submenu.length ? 'dropdown-button' : ''}}" data-activates="{{item.Submenu.length ? 'administration' : ''}}">
      <span ng-bind-html="item.Name"></span>
      <ul ng-if="item.Submenu.length>0" id="administration" class="dropdown-content">
        <li ng-repeat="subItem in item.Submenu"><a ng-href="{{subItem.Name}}" ng-bind-html="subItem.Description">{{subItem.Description}}</a></li>
      </ul>
    </li>
  </ul>
</div>
</nav>

Answer №2

  • Consider modifying the conditional statement from ng-if="item.Submenu.length>0" to ng-if="item.Submenu"
  • Alternatively, you can create a new property within the submenu object such as show = true, and then utilize ng-if="item.submenu.show".

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

Tips for working with JSON in jQuery/JavaScript

My setDefaultPoint controller returns a map in JSON format. Below is the code: def setDefaultPoint = { if (springSecurityService.isLoggedIn()) { def officeId = params.officeId def officeRoleInstance=OfficeRole.get(officeId) ...

What ways can we implement identification features in Flutter Web applications, such as adding an ID or name property?

While developing a Flutter Web application, I am exploring a Web-UI-Testing framework that is Selenium-based. Unfortunately, I am struggling to locate an HTML element that represents a specific flutter widget by its id or name attribute. The widget key doe ...

What is the best way to make an HTML form show fields depending on certain conditions?

Initially, I created an index page containing a form with various fields. The utility was built to handle all the fields, but now there's been a change in requirements. What I need is for only the Controller Type and Test Type fields to be displayed f ...

Numerous Radio Buttons

I am currently working on creating a quiz similar to those found on Buzzfeed and Zimbio. I apologize if this question has been asked before, but despite my efforts in searching, I have not been able to find the answer I am looking for. In this quiz, partic ...

Is there a way to flip a figure that is flipped upside down?

I'm currently working on creating a map using a json file to go from d3.js to Three.js. However, when the map is displayed, it appears upside down. I'm wondering if there is a way to flip it so that it displays correctly. As a newcomer to d3 and ...

Using the useNavigation Hooks in React Js, learn the process of sending JSON data efficiently

This is the custom Json file I developed for my application. export const Data = [ { id: 1, title: "Title 1", description: "Description 1 Data", }, { id: 2, title: "Title 2", ...

Passing a JSON or dictionary variable to an operator in Airflow: A practical guide

I am struggling to find a way to successfully pass a registered dictionary as a variable in the parameters of an operator to launch a databricks notebook. Despite my attempts, I have not been able to make it work. Here is an example of the variable saved ...

What is the best way to specify a function parameter as a Function type in TypeScript?

I'm currently delving into the world of TypeScript and I am unsure about how to specify a function parameter as a function type. For instance, in this piece of code, I am passing a setState function through props to a child component. const SelectCity ...

Switch all occurrences of https URLs with <a> using the stencil technology

I am encountering an issue with replacing the answer retrieved from an API and formatting it correctly answerFromAPI = "textword textword textword textword textword.\n\nFeel free to ask me questions from this site:\nhttps://google.com &bso ...

Applying CSS styles to a class dynamically using JavaScript

Is there a way to dynamically add a new CSS property to an existing class using JavaScript? Let's say I have a class called .test with some pre-defined styling. How can I append the property color: blue; to this class using JavaScript? const elm ...

If the form is empty, clicking on the Login button will direct you to the page. It is necessary for an error to occur

What should happen when the form is empty and the Login button is pressed? Currently, the page opens without any errors. However, I want to display an error message under such circumstances. How can I modify the function to achieve this? const login = (e ...

Comprehending the significance of *this* within class structures

I've got this code snippet below. class Node { constructor(value, parent, possibleChildren = []) { this.value = value; this.parent = parent; this.children = [] this.setChildren(possibleChildren); } setChildren(possibleChil ...

SquirrelFish appears to be lacking "bind()", so how can one attach a JS callback to "this" in its absence?

Does anyone know a way to attach a JS callback to "this" without using "bind()"? Based on Samsung specifications: In 2013 with V8: everything functions as expected (refer to linked screenshot, too large to include here) In 2012 with SquirrelFish: encoun ...

What steps do I need to take to successfully integrate Firebase authentication with Angular2 FINAL?

After upgrading to Angular2 Final, I completed the migration project steps to transition everything over. Surprisingly, there were no errors during authentication; however, the issue arises post-authentication. Upon redirection back to the page, the authen ...

JavaScript organizes URLs based on their domain and directory

Is there a way to group URLs from a sorted list by domain and directory? When two URLs share the same directory (the first one after the domain), they should be grouped together in an array; If URLs have different first directories but the same domai ...

Turned off jquery on a specific div in order to resolve compatibility problems with Vue.js

Currently, I am working on a Drupal project which includes JQuery in all pages. We have recently introduced Vue.js for creating dynamic components directly in the HTML pages (not for building a single-page application). However, we are facing an issue whe ...

What is the best way to assign table rows to various interfaces in typescript?

Assuming I have the interfaces provided below: export interface IUserRow { id: string, state: string, email: string, } export interface ITableRow { id: string, [key: string]: any; } export type Rows = ITableRow | IUserRow; // additio ...

Tips for creating an exceptional DTO request class:

I am looking to create a DTO class that can accurately represent a JSON request body. My goal is to have this class be fully immutable by utilizing final fields. While I have come across implementations using @JSONCreator with an all-args constructor, I ha ...

A guide on testing mouse clientY in React using JEST for effective testing

useEffect(() => { const mouseHandler = (event: MouseEvent) => { menuData.forEach((element) => { if (element.hasActiveDropdown && event.clientY > 50) { handleCloseDropDown(); // handleDropDown('0') ...

Organizing and managing one-on-one table tennis matches using a customized data structure. Leveraging the power of Vue, JavaScript, and

Seeking advice on the best approach for storing table tennis match data in a web application. I currently have a method in place that works, but I'm open to suggestions for improvement. Here is my current idea: matches: [ { id: 1 datePlayed ...