A step-by-step guide on importing data from an external nested JSON file and displaying its contents

CODE

Having trouble displaying the results from a JSON object on my view page. The screen appears empty, but I can see the data in the console. When using ng repeat, it shows an error "Duplicate Key in Repeater."

The main requirement is to print the title from the JSON file and have it display when clicked, showing the Title as "example".

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

appModule.factory('dataFactory', ['$http', function($http) {
  var factory = {
    itemDetails: function() {
      return $http({
          url: "action.json",
          method: "GET",
        })
        .then(function(response) {
          return response.data;
        });
    }
  };
  return factory;

}]);


appModule.controller('DataController', ['$scope', 'dataFactory', function($scope, dataFactory) {
  var promise = dataFactory.itemDetails();

  promise.then(function(data) {
    $scope.itemDetails = data;
    console.log(data);
  });
  $scope.select = function(item) {
    $scope.selected = item;
  }
  $scope.selected = {};
}]);
<!DOCTYPE html>
<html ng-app="appModule">

<head>
  <meta charset="utf-8" />
  <title>Dynamic Title</title>

  <link data-require="bootstrap-css" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />

  <script data-require="jquery" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
  <script data-require="bootstrap" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body>
  <div ng-controller=DataController>
    <h3>Load Title Dynamically</h3>
    <div class="row">
      <div class="col-md-4">
        <div class="panel panel-default">
          <ul class="list-group">
            <a class="list-group-item" ng-click="select(item)" ng-repeat="item in itemDetails">{{item.title}}</a>
          </ul>
        </div>
      </div>

      <div class="col-md-8">
        <div class="panel panel-default">
          <h2>Title: {{selected.title}}</h2>
        </div>
      </div>
    </div>
  </div>
</body>

</html>

Action Data

{

   "product": [{
         "title": "Product View",
         "path": "test1"

      },

      {
         "title": "Product Add",
         "path": "2"

      },
      {
         "title": "Product Update",
         "path": "test3"


      },

      {
         "title": "Product delete",
         "path": "test4"

      }
   ],

   "page": [{
      "title": "About us"
   }]

}

Answer №1

To optimize your code, consider using two nested ng-repeat directives.

  <div ng-repeat="(key,item) in itemDetails">
      <a ng-repeat="i in item">
        {{i.title}}
      </a>
   </div>

Check out the demo here

Answer №2

Within your JSON data, there are key values for products and pages. By utilizing a promise, you can retrieve the entire object and then iterate through to access the individual product objects and their corresponding titles.

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

A step-by-step guide on displaying a loading spinner during the retrieval and assembly of a component framework (Astro Island) with Vue and AstroJS

Here is the astro code I'm working on: --- import BaseLayout from '../../layouts/BaseLayout.astro'; import ListadoProfesionales from "../../components/pages/ListadoProfesionales/ListadoProfesionales.vue"; --- <BaseLayout title= ...

Caution: An invalid next.config.js file has been detected while running the Next.js project

Whenever I try to run my project, I encounter the following three warnings: 1- warn - We found some invalid options in your next.config.js file. The property webpack5 is not recognized and may cause issues (allowed properties are: amp, analyticsId, assetP ...

The error occurred in Angular with the [dateclass] class specifically within the mat-calendar

I'm currently working on creating a calendar that allows for multiple date selections. I came across a helpful resource on StackBlitz Here is the code snippet for my AppComponent: isSelected = (event: any) => { const date ...

Are toggle functionalities triggered when an element is clicked?

How come the span triggers functions a and b when first clicked, is there a way to set it up so that it calls function a on the first click and then function b on the second click? function a(id) { $.post("url.php", {'id':id}, function() { ...

Rendering components before ComponentDidMount runs and Axios handles state updates

When I try to pass the gifs state to my GifList component in the render method, I encounter an issue. It seems that when trying to access the array within the component through props, it is returning as undefined. After investigating further, I noticed t ...

Exploring the depths of JavaScript JSON elements

After processing my PHP code, it generates a JSON output that contains multiple entries in the same structure. Here is an example with two entries: { "0": { "campaign_id": "31", "title": "new title", "description": "new descrip ...

Tips for adding a dynamic variable into a react JSX map function

I have a component that receives a props with the value of either 'A', 'B', or 'C' based on the selection made in the parent element. The challenge is to use this props to dynamically select an option list locally, instead of ...

Exploring more effective methods for iterating and showcasing individual elements sequentially with AngularJS

I am currently in the process of developing an application that involves incorporating animations, and I am seeking to enhance its performance. My goal is to navigate through a sequence of divs at specific time intervals while displaying one at a time. Add ...

Is it possible to obtain the Apache server status (mod_status) output in JSON or XML format?

Exploring Apache's "mod_status" Feature: One of the functionalities provided by Apache is the "mod_status", which allows users to monitor the current status of their server. When accessed, it presents a wealth of information similar to the sample pag ...

Parsing JSON stored in local storage and converting it to a Fabric JS object - JSON generated from form inputs

Currently, I am facing some challenges while using Fabric js for a project that I am working on. My main goal is to create a form where users can input details, which will then be converted into a JSON object and stored locally. After submitting the form, ...

Scrolling through a list in Angular using cdk-virtual-scroll-viewport while selecting items via keyboard input

Looking to implement a customized Autocomplete feature. As the user begins typing, a small window should appear with selectable options. I want users to have the ability to navigate and select an option using their keyboard. For instance: - User types "H ...

Determining the Size and Color of Squares in a Treemap Based on Content with D3.js

I encountered an issue with a treemap visualization. I came across an example that is similar to my situation, which can be viewed here: In the demo, you can see that the size of each square in the treemap is determined by the content size. However, all s ...

Where can I find the complete specification for the Calendarific JSON format?

I am interested in utilizing the Calendarific API for calculating working days in different regions. While the JSON response is informative, I am unable to locate a comprehensive definition of the fields within the API. In particular, I am seeking detail ...

What is the best method for incorporating a JavaScript redirect into an Android WebView?

My issue involves loading a page into a webview. Typically, when I use the code webview.loadUrl(url); it functions as expected. The url contains a javascript code that redirects the page. Here is the javascript code: <script type="text/javascript"> ...

methods for transferring JSON data from JavaScript to PHP

I am trying to figure out how to parse JSON data from JavaScript to PHP. Here is my JavaScript code: var Dataconvert; var asetid = new Array(); $("#simpanmodifikasi").click(function(){ var table = $('#tableasal tbody' ...

React - output from forEach() function is not defined

I am facing a challenge in rendering prop values from a nested object. There are two issues that I'm encountering: 1. The JSX code line (with variables) is not showing up in the browser 2. When I console log the variables with .forEach() methods, th ...

JavaScript array remains unchanged

I have a sample of JSON data saved in the "data" variable. Here is the FORMAT : { "0" : {"names":"Pooja, Trivedi"}, "1" : {"names":"Pooja, Rooster"} } My objective is to create a map that can calculate the frequency of each name: Pooja = 2 Triv ...

One should refrain from loading the API in Angular when there is no data present, by utilizing the global.getData method

Check out this code snippet: loadNextBatch() { console.log('scrolldown'); this.pageIndex = this.pageIndex + 1; this.global.getData(`/conditions/latest?start=${this.pageIndex}&length=${this.pageSize}`) .pipe(take(1)).subscr ...

What could be causing my $resource error handler not to be invoked even though I have a responseError interceptor set up?

As I develop my first Angular application, I've encountered a challenge. Within my AngularJS resource, I call the .get method with both success and error callbacks, like this: var new_uptime = Uptime.get({}, function(){ console.log("new_uptime", ...

Locate records in MongoDB by leveraging the power of Mongoose

Managing two distinct databases, one for products and another for categories. The product schema is defined as follows: const productSchema = new mongoose.Schema({ name: { type: String, required: true }, description: { type: String, required: true }, ...