What is the process for extracting information from a Json file and showcasing it in an HTML dropdown menu?

I recently created a basic HTML page using AngularJS that features a dropdown menu displaying manufacturer names. Upon selecting a manufacturer, the corresponding ID is shown in a text box below. I utilized the ng-repeat directive for displaying the manufacturers' names in the dropdown and the ng-model directive to display the selected manufacturer ID.

Below is my HTML code:

<!DOCTYPE html>
<html ng-app="jsonapp">
<head>
<script src="angular.min.js"></script>
<title></title>
</head>
<body> 
<div ng-controller='JsonController'>
    <span>Please select a Manufacturer:</span>

     <li ng-model="Manufacturers" ng-repeat="Manufnames in Manufacturers" style="width:350px;">
            {{Manufnames.ManufacturerName}}
     </li>  
// The dropdown menu displaying Manufacturer Names
    <input type="text" /> // Displaying the corresponding Manufacturer ID 
</div>
<script>
    var app = angular.module('jsonapp', []);
    app.controller('JsonController', function ($scope, $http) {
        $http.get('Pipes.json') 
        .success(function (response) { $scope.Manufacturers = response.Pipesmanuf; });
    });
    </script>
 // I have both the JSON and HTML files stored in the same folder; so, passing the JSON filename directly to the http.get() function to retrieve data.
</body>
</html> 

// My JSON file contains the following data:

{
"Pipesmanuf": [
    {
        "ManufacturerId": 1,
        "ManufacturerName": "Avonplast",
        "Products": "PIPES",
        "ManufacturerLogo": "C:\Users\Suprith\Desktop\Manufacturerlogos\Pipes\avonplast.jpg"
    },
    {
        "ManufacturerId": 2,
        "ManufacturerName": "BEC",
        "Products": "PIPES",
        "ManufacturerLogo": "C:\Users\Suprith\Desktop\Manufacturerlogos\Pipes\BEC.png"
    }
]
}

As a newcomer to Angular JS, I would appreciate any suggestions on how to load data from a JSON file and display it using HTML dropdowns or lists.

Answer №1

Your JSON contains invalid directory paths with backslashes \ acting as escape characters, causing parsing issues. To fix this, simply update your JSON to:

{  
   "Pipesmanuf":[  
      {  
         "ManufacturerId":1,
         "ManufacturerName":"Avonplast",
         "Products":"PIPES",
         "ManufacturerLogo":"C:\\Users\\Suprith\\Desktop\\Manufacturerlogos\\Pipes\\avonplast.jpg"
      },
      {  
         "ManufacturerId":2,
         "ManufacturerName":"BEC",
         "Products":"PIPES",
         "ManufacturerLogo":"C:\\Users\\Suprith\\Desktop\\Manufacturerlogos\\Pipes\\BEC.png"
      }
   ]
}

This adjustment will correctly handle the escape character.

To display the list in a dropdown, utilize a similar loop like so:

<select>
    <option ng-repeat="Manufnames in Manufacturers">{{Manufnames.ManufacturerName}}</option>
</select>

For reference, check out the Plunker example: http://plnkr.co/edit/LXvFNZBVzCIZot96JhgP?p=preview

Answer №2

Make sure to check out the official guide at: https://docs.angularjs.org/tutorial/step_01.

They cover a similar concept in step 11.

Essentially, for a more efficient and reusable solution, it's recommended to use a service to fetch data from your file. Then, inject this service into your controller to retrieve and display the data in your view. The tutorial should provide you with the necessary guidance. Best of luck!

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

Using jQuery to create clickable URLs within a rollover div

I am looking to have the div appear on a mouse over effect in the following code. Is there a way for me to input a url based on the data that is passed to it? Anchorage: ["Anchorage", "(555)555-5555"], (This represents the data being posted) AtlanticCit ...

Convert a file into an empty array when sending a post request from Angular to Laravel

I am currently working on a simple Laravel 5 post request that aims to achieve the following tasks: Save some data to a database. Store a file (image) in public storage with a name consisting of 20 random numbers followed by '.jpg'. Save a URL ...

Ways to troubleshoot the error message 't.rangeslider is not a function' in which rangeslider is a personalized function

I'm experiencing an issue with a function assigned to a variable that is throwing an error. Here is the code snippet: $(".sliderRange").each(function() { var t = $(this); t.rangeslider({ polyfill: !1, onSlide: function(e, a) { var n = ...

Is there a way to mock a keycloak API call for testing purposes during local development?

At my company, we utilize Keycloak for authentication integrated with LDAP to fetch a user object filled with corporate data. However, while working remotely from home, the need to authenticate on our corporate server every time I reload the app has become ...

What methods can I use to integrate modifications to a library into my application?

I have encountered some issues with a library that I am currently using. As a newcomer to this project, I am unsure of how to proceed. Specifically, the problematic library is related to the windows-registry. I have identified two fixes that need to be ma ...

Unable to obtain the accurate response from a jQuery Ajax request

I'm trying to retrieve a JSON object with a list of picture filenames, but there seems to be an issue. When I use alert(getPicsInFolder("testfolder"));, it returns "error" instead of the expected data. function getPicsInFolder(folder) { return_data ...

What is the best way to integrate AngularJS with jQuery?

Lately, I've been incorporating AngularJS into my project. In the past, I've written various prototypes and standalone JavaScript functions, such as (Node.js + socket.io functionality). However, I am currently facing some challenges when it come ...

Creating a text slider in Javascript with dual quote sets is a fun and interactive

I am looking to create a dynamic quotes text slider with two sets of data. For reference, check out the fiddle link here: https://jsfiddle.net/628r3t1h/ (function() { var quotes = $(".quotes"); var quoteIndex = -1; function showNextQuote( ...

Customize Date Display in Material-UI DataGrid

How do I change the date format in MUI DataGrid from mongo's format to moment.js? In addition, I would like to add a new field with an edit icon that, when clicked, will redirect to the edit page. Here is what my code looks like: const columns = [ ...

Unexpected behavior encountered with JQueryUI modal functionality

Today marks my first experience with JqueryUI. I am attempting to display a conditional modal to notify the user. Within my ajax call, I have this code snippet: .done(function (result) { $('#reportData').append(result); ...

Grouping data in C# using LINQ while also incorporating JSON

Let's consider a scenario where we have a list of OrderItems defined as follows: public class OrderItem { public long Id { get; set; } public long OrderNo { get; set; } public string OrderEvent { get; set; } public string OrderData { g ...

Highcharts introduces a new feature with the addition of three buttons in the Legend: Hide, Remove,

I'm looking to enhance the Legend by adding 3 buttons: Hide, Remove, and Settings. The Hide button should hide the series/indicator upon click event, The Remove button should remove (not just hide) the series/indicator upon click event, The Settings ...

Encountering an issue with the history module when utilizing the webpack dev server

I am encountering an issue while trying to run webpack dev server. The history functionality was working fine until I started using the webpack module. A warning message appeared in my console: WARNING in ./src/history.js 2:15-35 export 'createBrows ...

Don't initiate the next fetch until the previous one has completed

I am currently working on sending a list of data to Google Cloud. The code I have been using is as follows: const teams = ['LFC', 'MUFC', 'CFC']; teams.forEach(team => { fetch({ url: URL, method: 'PUT ...

Creating an HTML table to showcase array data stored in a session

After successfully storing data from an HTML table on page 1 in an array object (arrData) and saving it to session storage, the next challenge is how to display this data on a new HTML table on page 2. I am new to JavaScript, so any help would be appreciat ...

Passing events from Vue to child components

Looking for a way to make clicking on the outer pill element have the same effect as clicking on the checkbox itself? Check out this HTML code that renders these little boxes: https://i.sstatic.net/hspnF.png <div class="token-checkboxes"> <spa ...

Error: The 'ActivitiesClient' object does not contain a property named 'base_url'

Although this question may have been answered before, I have not been able to identify my mistake despite searching through numerous questions. Here is my script: import json from config import BASE_URL from utils.request import APIRequest class Activi ...

AngularJS testing typically involves the use of the inject module injection process

Currently, I am working on testing a service called documentViewer, which relies on another service named authService. angular .module('someModule') .service('documentViewer', DocumentViewer); /* @ngInject */ function Do ...

I need to find a way to properly test a recursive, async JavaScript function by utilizing fake timers

I've been working with a basic recursive function that performs as expected when run. To thoroughly test its operation at each stage, I want to utilize Sinon's fake timers. Unfortunately, it seems that the fake timers are only affecting the init ...

Sorting through a JavaScript array

I am facing a peculiar problem while trying to filter an array in TypeScript. Here is the structure of my object: Sigma.model.ts export class Sigma { sigmaId: number; name: string; userId: number; starId: string; } `` The starId property contains com ...