Struggling to display a navigation menu on angular 1 with complex nested json structure

I have set up a navigation bar using JSON data fetched by an Angular service. Everything is working fine with my service and controller, but I am facing difficulty in displaying the nested JSON data in my view. Here is the JSON data:

{
    "menu": [
        {
            "name": "Electronics",
            "link": "1",
            "sub": [
                {
                    "name": "Mobiles",
                    "link": "1.1",
                    "sub": [
                        {
                            "name": "Samsung",
                            "link": "1.1.1",
                            "sub": null
                        },
                        {
                            "name": "Apple",
                            "link": "1.1.2",
                            "sub": null
                        },
                        ...
                    ]
                },
                ...
            ]
        },
        ...
    ]
}

I can successfully see all the data in the console, but need assistance with rendering the data in the view using ng-repeat.

For your reference, here is the controller and Factory code: Factory:

( function ()
{
    angular.module( "myApp" )
    .factory( "navService", function ( $http )
    {
        function getNavItems()
        {
            return $http.get( '../data/navData.json' );
        };
        return {
            getNavItems: getNavItems
    };
} );
}()

Controller:

( function ()
{
    angular.module( "myApp" )
    .controller( "NavController", function ( $scope, $http, navService )
    {
        navService.getNavItems().then( function ( menu )
        {
            $scope.menu = menu.data;
            console.log( menu.data );
        } );
    } );
} ());

Any help would be appreciated. Thank you.

Answer №1

Here is the proper approach:

  navService.getNavItems().then( function ( result)
  {
       $scope.menu = result.data.menu;
  });

Answer №2

After encountering the same issues in my local environment and experiencing errors, I was able to resolve them successfully.

If you are using camel case for the controller name, it is essential to include use strict; at the beginning of both the controller and services JavaScript files.

Below is the solution code provided:

Json Data file : navData.json

{
    "menu": [
        {
            "name": "Electronics",
            "link": "1",
            "sub": [
                {
                    "name": "Mobiles",
                    "link": "1.1",
                    "sub": [
                        {
                            "name": "Samsung",
                            "link": "1.1.1",
                            "sub": null
                        },
                        ... (additional menu items)
                    ]
                },
                ... (additional menu categories)
            ]
        }
    ]
}
... (omitting additional HTML and JavaScript code snippets for brevity)

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

Establish an HttpOnly cookie using JavaScript

Is it possible to convert a non-HttpOnly cookie into an HttpOnly cookie using JavaScript? ...

Tips on invoking a JSP and Servlet from JavaScript by passing in a parameter

Check out the code below for calling JavaScript functions: <td><input type="button" name="edit" value="Edit" onclick="editRecord(<%=rs.getString(1)%>);" ></td> <td><input type="button" name="delete" value="Delete" onclic ...

DreamFactory's REST API POST request for rest/user/session consistently encounters errors in Internet Explorer 9

In Firefox, Chrome, and Safari, the initial POST rest/user/session request works perfectly fine. However, in Internet Explorer 9, it consistently returns an error. When the dataType is specified as "json," IE9 encounters a 'no transport' error w ...

Is the Angular Library tslib peer dependency necessary for library publication?

I have developed a library that does not directly import anything from tslib. Check out the library here Do we really need to maintain this peer dependency? If not, how can we remove it when generating the library build? I have also posted this question ...

Conceal specific pages within the DataTable without deleting them

Currently, I am facing an issue where the dataTable paginates and removes the DOM pages along with the data. My goal is to extract all the data from the dataTable and convert it to JSON without losing access to the DOM when pagination occurs. I want to m ...

Is there a workaround for retrieving a value when using .css('top') in IE and Safari, which defaults to 'auto' if no explicit top value is set?

My [element] is positioned absolutely with a left property set to -9999px in the CSS. The top property has not been set intentionally to keep the element in the DOM but out of the document flow. Upon calling [element].css('top') in jQuery, Firef ...

Can you provide instructions on how to use JavaScript to click and hold a button for a specific duration?

Is it possible to use jQuery to create a button that, when guest button number 1 is clicked, will automatically click and hold down button number 2 for about 3 seconds? I have tried using the mousedown() and click(), but they only register a click, not a ...

What is the best tool to develop my AngularJs class library (service/factory/provider)?

I am currently working on my main service: (function (angular) { "use strict"; angular .module("app") .service("mainService", mainService); mainService.$inject = ["classLibrary"]; function mainService(classLibrary) { this.person = new clas ...

When trying to show a Vue view, there was an issue with reading properties of null, specifically the 'style' property

I am experiencing an issue with a header that has an @click event in the body. Instead of displaying a Vue view upon clicking, I am encountering the following error: Cannot read properties of null (reading 'style') Upon researching on Stack Ove ...

Issue with Sliding Transition in React Material UI Drawer Component

I developed a custom drawer component for my React application const CustomSidebar = () => { return ( <Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} > <Box> <Navigator / ...

What is the best method for converting a complex JSON structure, including arrays, integers, dictionaries, strings, and null values, into a pandas

I have the following JSON structure, { 'total_numbers': 2, 'data':[ { 'col3':'2', 'col4':[ { 'col5':'P', 'col ...

I am looking to incorporate a child row for each tr element within AngularJS

Here is the code snippet I have: <td class="name"> <i class="mdi mdi-plus s16" ng-click="childRowToggle($event)"></i> <div ng-click="details(assets.code)">{{assets.name}}</div> <span class="seco ...

No reply received on the web browser

I have written a code that is intended to read a JSON file and display it in the browser. The code is functioning correctly as it prints the data to the console, but for some reason, the data is not displaying on the browser. app.post("/uploadfile&q ...

Include a header in the API HTTP call for Angular 2 and Ionic 2

Working on my Ionic 2 app, I am using Angular 2 Http to retrieve JSON from an API. However, I am struggling to send the app-id, app-key, and Accept as headers in the main code snippet below: import {Component} from '@angular/core'; import {NavC ...

"Embrace the power of Ajax and JSON with no regrets

function register() { hideshow('loading', 1); //error(0); $.ajax({ type: 'POST', dataType: 'json', url: 'submit.php', data: $('#regForm').serialize(), su ...

JSON manipulation: Snowflake flattening with dynamic key changes

I am facing an issue with a table in Snowflake that has a similar structure to the one shown below, ---------------------------------------- Name | Number ---------------------------------------- Dim_1 | {'Table_1': 100} Dim_1 | {'Table_1&a ...

What is the best way to emphasize a specific data point within a chart created with chartjs, especially when the data is sourced from a JSON

// Here I am retrieving another set of data in JSON format from a PHP file $(document).ready(function () { showGraph(); }); function showGraph() { $.post("phpfile.php", function (data) { console.log(data); var name = []; v ...

Problem with Ionic Material's item class

Currently, I am working on the Ionic material demo app and encountering an issue. When I do not use the "item class," everything works fine, but the UI does not appear as expected because that class is missing. The code is as follows: <div class ...

Make sure to allow the async task to complete before beginning with Angular JS

As I develop an app using MobileFirst v8 and Ionic v1.3.1, I encounter issues with timing in my code execution. Specifically, when the application initiates, the regular ionic angular code within my app.js file runs. This section of the code handles the i ...

Looking to implement a delay in the model popup using Pure JavaScript

Looking for a method to implement a delay in the popup... I've tried a few solutions without success. What's the secret to adding a delay to the modal below? Any help is greatly appreciated. var modal = document.querySelector(".modal"); var t ...