Adding choices to dropdown menu in AngularJS

As a beginner in AngularJs, I am struggling with appending options to select boxes created by javascript. Below is the code snippet that is causing the issue.

var inputElements = $('<div><label style="float:left;">' + i + '</label><select ng-model="object" class="form-control sel" style="width:300px; float:right; margin-right:75px;"> <option>select</option></select></div></br></br>');
var temp = $compile(inputElements)($scope);
$('#projOrder').append(temp);
$scope.object = object;
//for(var opt=0; opt<selOptLabels.length; opt++) {
$('.sel').append('<option ng-repeat="obj in object" value="'+
{{obj.value}}+'">'+{{obj.value}}+'</option>');

I encountered this error message: "SyntaxError: invalid property id"

Greetings, here is an example of some JSON data. This is just a snippet from my larger dataset.

    "ProjectOrder": {
"Connect direct required": {
  "value": "N",
  "id": "STR_15523_62"
},
"Cores": {
  "value": ".5",
  "id": "NUM_15523_50"
},
"Permanent data in GB": {
  "value": "100",
  "id": "NUM_15523_56"
},
"Description": {
  "value": "AZBNL azbngb",
  "id": "STR_15523_2"
},
...
"WORK data in GB": {
  "value": "100",
  "id": "NUM_15523_55"
}

}

Now, my task is to generate input fields and dropdown menus (if applicable) using the provided JSON data.

Answer №1

Constructing HTML manually like this is not recommended. It's better to utilize a template and delegate the heavy lifting to the template engine.

I observed that you are using object as the ng-model. It would be more appropriate to have a separate variable to store the selected value.

Here is an improved approach for achieving this in an .html file:

<div ng-repeat="object in listOfObjects"
    <label style="float: left">{{ $index }}</label>
    <select ng-model="selectedValues[$index]" class="form-control sel"
        style="width:300px; float:right; margin-right:75px;"
        ng-options="obj.value for obj in object"></select>
</div>

Then, in your JavaScript controller:

// array to hold selected values
$scope.selectedValues = new Array(list.length);
// list of objects
$scope.listOfObjects = list;

This may not be the most elegant solution, but essentially, I've created an array with the same length as the list of objects. In Angular templates, within an ng-repeat, $index is a special variable that keeps track of the current index in the loop.

Hence, when a user modifies the selected value of the 3rd select box (index 2), $scope.selectedValues[2] will capture the chosen option.

EDIT: Converting JSON to an array example:

var list = Object.keys(json).map(function(jsonKey) {
    return {
        name: jsonKey,
        label: json[jsonKey].label,
        value: json[jsonKey].value
    };
});`

Answer №2

There are multiple reasons why that approach may not be effective. The code provided is flawed due to the template brackets being appended to the HTML string...

$('.sel').append('<option ng-repeat="obj in object" value="' +{{obj.value}}+'">'+{{obj.value}}+'</option>');

Is there a specific rationale behind constructing your markup in JavaScript?

It's generally recommended to avoid using jQuery within Angular controllers. If jQuery is loaded, the jQuery object can be accessed via angular.element, otherwise Angular utilizes jQuery light.

Instead of delving into other issues here, I have prepared a simple example showcasing how a select element functions in Angular:

https://codepen.io/parallaxisjones/pen/BRKebV

Furthermore, it would be beneficial to refer to the Angular documentation prior to asking queries on platforms like Stack Overflow. The documentation includes a clear demonstration of utilizing ng-repeat within a select element. https://docs.angularjs.org/api/ng/directive/select

EDIT: My codepen has been updated with an illustration of fetching JSON data through an HTTP GET request

EDIT: The codepen has been revised with an example of iterating over an object using (key, value) syntax within ng-repeat for JSON data

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

Combine arrays of JSON data within a JSON object using JavaScript

Looking for help with reformatting a JSON response {"result":[["abc","de"],["fgh"],["ij","kl"]]} Interested in transforming the response to: {"result":["abc","de","fgh","ij","kl"]} What's the best way to accomplish this task? ...

Utilizing PHP and AJAX to Extract Information from a MySQL Database

My goal is to fetch data from a MySQL database hosted on a webserver and display it in an HTML table. I've been following an example on W3Schools, but I'm facing issues retrieving the data successfully. Here is the source code: (HTML) <html& ...

I am looking for some guidance on utilizing the data obtained from a JSON response in a separate HTML file with AngularJS. Can

Upon user login, various data is sent back to different HTML pages that must be used in conjunction with a subsequent POST to a URL on another page. For example, after authentication, user information such as userid, sex, and other data are retrieved for u ...

Transform the Hue or Color of a PNG using ASP.Net, VB.Net, and jQuery

I am currently developing a web page that can combine multiple PNG images into one flat image for users to download. I am looking to incorporate a feature that allows for hue or color adjustments, similar to the color balance functionality in Photoshop. ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

How to integrate an AngularJS page into a Node application

Exploring the realm of single page web apps with node, angular, and jade has been an interesting journey for me as a newcomer to angular. I am currently faced with a dilemma regarding my app.js file - how can I ensure that my initial page template loads fr ...

Calculating the combined cost of items in the shopping cart

I encountered a small problem while working on my project. I'm trying to calculate the total price of all items in the cart by summing them up, but my mind is drawing a blank at the moment. Below is the code snippet I am currently using: const { ca ...

How do you vertically span a grid element across 3 rows using Material UI?

This particular scenario may appear to be straightforward, but the official documentation of Material UI lacks a clear example on how to achieve this. Even after attempting to nest the grid elements, I encountered an issue where the grid element on the ri ...

Error: Unable to access property of an undefined value (ExpressJS/POST)

I have gone through all the similar questions but none of the solutions are working for me. I am facing an issue with my node js app where I am unable to print the input text from a form while using body-parser. Here is my index.ejs file: <fo ...

When trying to link a Redis microservice with NestJS, the application becomes unresponsive

I am attempting to create a basic hybrid app following the guidance provided by Nest's documentation, but I have run into an issue where the app becomes unresponsive without any errors being thrown. main.ts import { NestFactory } from '@nestjs/c ...

Creating dynamic components in ReactJS allows for versatile and customizable user interfaces. By passing

Within the DataGridCell component, I am trying to implement a feature that allows me to specify which component should be used to render the content of the cell. Additionally, I need to pass props into this component. Below is my simplified attempt at achi ...

NodeJS is constantly refreshing the data in the database table

Every day, I use a cron job to scrape data and insert it into a database. However, I'm facing an issue where the database results on the server do not refresh themselves after new data is inserted. I've come across 2 solutions here, but one was ...

Error: The PDFJS variable is not recognized when trying to load a PDF file

I've been experimenting with pdf.js to load PDFs into a web application in order to extract information in real-time. However, I keep encountering an error even with a simple example. I've attempted enclosing the code in $(document).ready() as a ...

Using React to map and filter nested arrays while also removing duplicates

Hello, I recently started working with react and I've encountered a challenge while trying to map an array. const fullMen = LocationMenuStore.menuItems['menu']['headings'].map((headings: any) => { <Typography>{ ...

Is there a way to assign a value to an element based on whether I receive a true or false?

How can I display a true or false value in HTML when binding it? Code: <li ng-if="display"><a ng-click="logout();" ><span class="icon mail"> </span>Logout</a></li> <li ng-if="!display"><a href="#/login">< ...

What steps should I follow to properly set up my tsconfig.json in order to ensure that only the essential files are included when executing npm run build

Introduction I am seeking guidance on how to correctly set up my tsconfig.json file to ensure only the necessary files are included when running npm run build for my projects. I want to avoid any unnecessary files being imported. Query What steps should ...

Running a cfquery in a cfc and passing parameters through AJAX

I am currently setting up a system to retrieve data from my ColdFusion database using JavaScript. However, I am encountering an error and unsure of its cause since I am relatively new to CF. The specific engine I am utilizing is ColdFusion MX 7. Below is ...

Tips for creating a responsive iframe without relying on aspect ratio assumptions

Is there a way to create a responsive iframe without relying on a fixed aspect ratio? The width and height of the content are unknown until rendering. Keep in mind, using Javascript is an option. For instance: <div id="iframe-container"> <i ...

Unable to assign value to a public variable in Angular

I am facing an issue where I am trying to retrieve a value from the localStorage and assign it to a variable. However, when I try to use that variable in functions, it is coming up as undefined. code export class DashboardService { public token: any; ...

What is the process for setting the spinner value according to the preferences value?

I am working on populating a spinner from a JSONArray and I need to set the spinner to a value stored in preferences. Specifically, I want to ensure that the spinner String "id" matches the "idlocatie" value stored in preferences. SharedPreferences mySh ...