How to retrieve nested menu items within the scope by utilizing JSON and AngularJS

I have recently started working with angular and am facing difficulty in accessing the submenu items within my angular application. While I can successfully access the top level menu items, I am struggling to retrieve the second level items.

Here is a snippet of my code:

HTML

<!DOCTYPE html>
<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.min.js"></script>
  <script src="app.js"></script>
</head>
<body ng-app="list">  
  <div ng-controller="ListCtrl">
    <ul>
        <li ng-repeat="menu in menus" id="{{artist.id}}">
            <a ng-href="{{menu.content}}">{{menu.description}}</a>
            <ul>
                <li ng-href="{{menu.content}}">{{menu.menu}}</li>
            </ul>
        </li>
    </ul>
  </div>
</html>

Javascript

// Code goes here
angular.module('list', []);

function ListCtrl($scope, $http) {
  $http({
    method: 'GET',
    url: 'menu.json'
  }).success(function(data) {
    $scope.menus = data.menus; // response data
    angular.forEach(data.menus, function(menu, index) {

    });
  });
}

JSON

{
   "menus":[
      {
         "id":"contact",
         "leaf":true,
         "description":"Contact Us",
         "link":"",
         "content":"contactUs.html",
         "cssClass":"static-content",
         "menu":null
      },
      {
         "id":"rules",
         "leaf":false,
         "description":"Sports Betting Rules",
         "link":"",
         "content":"",
         "cssClass":"",
         "menu":[
            {
               "id":"types",
               "leaf":true,
               "description":"Wager Types",
               "link":"",
               "content":"wagerTypes.html",
               "cssClass":"static-content wager-types",
               "menu":null
            },
            {
               "id":"odds",
               "leaf":true,
               "description":"Odds & Lines",
               "link":"",
               "content":"oddsAndLines.html",
               "cssClass":"static-content",
               "menu":null
            },
            {
               "id":"policies",
               "leaf":true,
               "description":"Rules & Policies",
               "link":"",
               "content":"rulesAndPolicies.html",
               "cssClass":"static-content rules-policies",
               "menu":null
            },
            {
               "id":"bonuses",
               "leaf":true,
               "description":"Sports Bonuses",
               "link":"",
               "content":"sportsBonuses.html",
               "cssClass":"static-content",
               "menu":null
            }
         ]
      },
      {
         "id":"conditions",
         "leaf":false,
         "description":"Terms & Conditions",
         "link":"",
         "content":"",
         "cssClass":"",
         "menu":[
            {
               "id":"termsOfService",
               "leaf":true,
               "description":"Terms of Service",
               "link":"",
               "content":"termsOfService.html",
               "cssClass":"static-content",
               "menu":null
            },
            {
               "id":"privacy",
               "leaf":true,
               "description":"Privacy Policy",
               "link":"",
               "content":"privacy.html",
               "cssClass":"static-content",
               "menu":null
            }
         ]
      },
      {
         "id":"view",
         "leaf":true,
         "description":"View in: Mobile | Full Site",
         "link":"",
         "content":"view.html",
         "cssClass":"static-content",
         "menu":null
      }
   ]
}

Answer №1

insert one more ng-repeat

 <!DOCTYPE html>
    <html>
    <head>
      <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.min.js"></script>
      <script src="app.js"></script>
    </head>
    <body ng-app="list">  
      <div ng-controller="ListCtrl">
        <ul>
            <li ng-repeat="menu in menus" id="{{artist.id}}">
                <a ng-href="{{menu.content}}">{{menu.description}}</a>
                <ul>
                    <li ng-href="{{submenu.content}}" ng-repeat="submenu in menu.menu">{{submenu.id}}</li>
                </ul>
            </li>
        </ul>
      </div>
    </html>

Answer №2

To access child elements, follow this structure:

<ul>
      <li ng-repeat="menu in menus" id="{{artist.id}}">
        <a ng-href="{{menu.content}}">{{menu.description}}</a>
        <ul>
          <li ng-repeat="submenu in menu.menu">
            <a ng-href="{{menu.content}}">{{submenu.description}}</a>
        </ul>
      </li>
</ul>

DEMO

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

app.controller("ListCtrl", ["$scope",
  function($scope) {

    $scope.menus =  
      [{
        "id": "contact",
        "leaf": true,
        "description": "Contact Us",
        "link": "",
        "content": "contactUs.html",
        "cssClass": "static-content",
        "menu": null
      }, {
        "id": "rules",
        "leaf": false,
        "description": "Sports Betting Rules",
        "link": "",
        "content": "",
        "cssClass": "",
        "menu": [{
          "id": "types",
          "leaf": true,
          "description": "Wager Types",
          "link": "",
          "content": "wagerTypes.html",
          "cssClass": "static-content wager-types",
          "menu": null
        }, {
          "id": "odds",
          "leaf": true,
          "description": "Odds & Lines",
          "link": "",
          "content": "oddsAndLines.html",
          "cssClass": "static-content",
          "menu": null
        }, {
          "id": "policies",
          "leaf": true,
          "description": "Rules & Policies",
          "link": "",
          "content": "rulesAndPolicies.html",
          "cssClass": "static-content rules-policies",
          "menu": null
        }, {
          "id": "bonuses",
          "leaf": true,
          "description": "Sports Bonuses",
          "link": "",
          "content": "sportsBonuses.html",
          "cssClass": "static-content",
          "menu": null
        }]
      }, {
        "id": "conditions",
        "leaf": false,
        "description": "Terms & Conditions",
        "link": "",
        "content": "",
        "cssClass": "",
        "menu": [{
          "id": "termsOfService",
          "leaf": true,
          "description": "Terms of Service",
          "link": "",
          "content": "termsOfService.html",
          "cssClass": "static-content",
          "menu": null
        }, {
          "id": "privacy",
          "leaf": true,
          "description": "Privacy Policy",
          "link": "",
          "content": "privacy.html",
          "cssClass": "static-content",
          "menu": null
        }]
      }, {
        "id": "view",
        "leaf": true,
        "description": "View in: Mobile | Full Site",
        "link": "",
        "content": "view.html",
        "cssClass": "static-content",
        "menu": null
      }]
     ; // response data


  }
]);
<!DOCTYPE html>
<html>

<head>
  <link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6d4d9d9c2c5c2c4d7c6f68598859883">[email protected]</a>" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
  <link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="60020f0f14131412011020534e534e55">[email protected]</a>" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.5/cosmo/bootstrap.min.css" />
  <link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85e7eaeaf1f6f1f7e4f5c5b6abb6abb0">[email protected]</a>" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />

  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="600a111505121920514e51514e53">[email protected]</a>" data-semver="1.11.3" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e3818c8c979097918293a3d0cdd0cdd6">[email protected]</a>" data-semver="3.3.5" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89e8e7eefce5e8fba7e3fac9b8a7bda7be">[email protected]</a>" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>

  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app='app'>
  <div ng-controller="ListCtrl">
    <ul>
      <li ng-repeat="menu in menus" id="{{artist.id}}">
        <a ng-href="{{menu.content}}">{{menu.description}}</a>
        <ul>
          <li ng-repeat="submenu in menu.menu">
            <a ng-href="{{menu.content}}">{{submenu.description}}</a>
        </ul>
        </li>
    </ul>
  </div>


</body>

</html>

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

"Upon triggering an event in AngularJS, the data attribute transitions to a state of truth

Here is the input I am using: <input type="checkbox" ng-model="area.id" data-id="{{area.id}}"/> Above this, there is some action with ng-click functionality. My goal is to gather all selected checkboxes' ids. However, after checking them, the ...

What are the best practices for utilizing "async/await" and "promises" in Node.js to achieve synchronous execution?

I'm fairly new to the world of web development and still grappling with concepts like promises and async/await. Currently, I'm working on a project to create a job posting site, but I've hit a roadblock trying to get a specific piece of code ...

Implementing CORS for controlling the origin of post requests

I am currently in the process of setting up a route at sub.domain.com/route. On domain.com, I have an Angular app that sends a post request to that endpoint. My main concern is whether I need to implement CORS on sub.domain.com/route to restrict post requ ...

Break down one object into an array consisting of multiple objects

I have a single object in the following array: [{"IP_Address":"33.4.160.5","originEmailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f050e020a1c2f18060303061c410c0002">[email protected]</a>"}] I am lookin ...

The 1st DIV element nudges the content within the 2nd DIV Element, causing it to stretch beyond the screen with 100%

I have gone through several other questions, but I am struggling to integrate the solutions into my problem. My main content DIV is set to 100% height and works perfectly fine until I add another element outside of the DIV towards the top of the browser. ...

Is there a way to transform a fixed parameter into a user input value and display the function's outcome on a different page?

I am in the process of developing a straightforward web application for book searching based on ISBN. The website will feature a text input field for entering an ISBN and a submit button. Essentially, a user can enter an ISBN in the designated box, click s ...

Configuring Node.js and express.js for my personal website to showcase my projects

I am new to node.js and I'm excited to implement it on my personal website as a way to start learning. I have successfully set up the node server, but I am struggling with setting up routing using express.js. All my files are typical static files like ...

What is the process for accessing a website using Java programming language?

Currently, I have a jar file up for sale that requires users to sign up on a particular website in order to download it. My issue lies in wanting to verify if purchasers have a valid login for the site when they run the jar file. Despite my attempts with h ...

Error: Attempting to access the 'map' property of an undefined variable, cart

My project consists of two main components, App.js and Cart.js. I am utilizing material-ui and commerce.js API for this application. import React , {useState , useEffect} from 'react' import Products from './Components/Products/Products&apos ...

Each time the button is clicked, the settings and values will rotate, creating a new

I'm looking to create a button system that transitions from "unmarked" to "form" and updates the database with each click. I want users to be able to cycle through the buttons, triggering a post request via ajax to update the associated ID in the data ...

The functionality of the bootstrap Dropdown multiple select feature is experiencing issues with the Onchange

Creating a Bootstrap Multiple Select Drop Down with dynamically retrieved options from a Database: <select size="3" name="p" id="p" class="dis_tab" multiple> <?php echo "<option>". $row['abc'] ."</option>"; //Fetching option ...

Is it possible for Web Service and MySQL to function on the iOs Simulator?

I am currently working on developing an app using XCode4. I have reached a point in my development process where I need to utilize web services to connect to a MySQL database for both retrieving existing user information and adding new account details. My ...

What is the best way to ensure bidirectional text appears correctly when two conflicting languages are combined, ensuring explicit directionality is set?

As I work on localization implementation, I encounter an issue with the directionality of mixed characters on the page. The text content is stored in a json file and inserted into the DOM using a Vue.js template. While individual characters display corre ...

Angular's ng-style directive is utilized for styling the ::after pseudo

I'm working on creating a unique dynamic horizontal rule. Here is the CSS code snippet: hr.my-hr:after{ content:'Generic' } And here is how I am implementing it in my template: <div ng-repeat="name in ['Adam', 'Colli ...

Utilize TypeScript to access scope within a directive

Is there a way to access the controller's scope properties using my custom TypeScript directive? For example, in this snippet below, I am trying to retrieve and log scope.message: /// <reference path="typings/angularjs/angular.d.ts" ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

Arranging data in a JSON array while handling null values in JavaScript

Here is my JSON array: var jData = [ {id: 1, parent: null}, {id: 2, parent: null}, {id: 3, parent: 1}, {id: 4, parent: 2}, {id: 5, parent: 2}, {id: 6, parent: 1}]; I would like to sort it in the following order (first by id then by parent): [ {id: 1 ...

Can custom directives incorporate comprehension expressions?

Is there a way to implement comprehension expressions similar to those used in ng-options, but for grouping radio buttons or checkboxes? app.js angular .module("app", []) .controller("controller", ["$scope", function($scope){ $scope.selec ...

Is it normal that my website isn't scrollable on an iPhone?

I have a hunch that the issue is related to the CSS, or perhaps it could be due to including the parallax JavaScript library. You can view the site at Below is the SASS code snippet: @import "compass/css3"; /* Sticky footer styles ---------------------- ...

Activate tooltip by clicking outside of the dropdown menu

I am experiencing an issue with a tooltip and a dropdown menu. Whenever I interact with the dropdown by clicking outside of it or inside its contents, the tooltip content is triggered again. For example, when I hover over the button, the tooltip triggers ...