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

Show real-time server responses using jQuery while waiting for the AJAX request to complete

I have a challenge in creating a function that displays the server response while waiting for Ajax to complete. Here's the scenario: I have selected 10 checkboxes. When I click the submit button, Ajax is triggered. On the server side, there is a loo ...

Picking and modifying a newly added HTML input element using Jquery

I am encountering a problem that I haven't been able to find a solution for through research or Google. I managed to successfully add multiple input boxes to my HTML/JQuery project, which are displaying correctly on the webpage. for (i = 0; i < ma ...

Mapping responses with objects in Spring Boot Api Client involves a sophisticated process that aims to convert list of objects into individual objects for better

How can I design a class to handle an API response that delivers individual objects instead of a list of objects? I am using Spring Boot and RestTemplate but unsure how to approach this situation. Here is an example response: { "status":200, "data":{ ...

Exploring Angular UI Router Testability Through Resolve

Looking for some assistance with my karma setup as I am still learning. Here are the routes that I have defined: angular .module('appRouter',['ui.router']) .config(function($stateProvider,$urlRouterProvider){ ...

Is there a way to convert an empty string to zero in MySQL?

Can you help with answering my question? My question pertains to saving an empty string "" value in my table and storing it as a 0 value in the MySQL database. Here is a visual representation: Table -> MySQL "" 0 Thank you for your assi ...

Incomplete data was retrieved from the localStorage

I am currently in the process of developing a mobile application using Phonegap version 1.4.1. I have encountered an issue on iOS (running on version 5.1) where the app fails to load all data from localStorage. Upon first use of the app, I set a flag in l ...

Direct users to a different page upon reloading the page in Django

Currently working on a web application with the Django framework. In one of the forms in my app, I am looking to automatically redirect to a new page upon reloading the current page, rather than when the form is submitted. Any insights from the community w ...

Exclude the file and directory patterns from being watched with PM2: ignore folder

I need help with configuring pm2 to stop monitoring folders that have names like cache or tmp. I've tried multiple approaches in my app.json configuration file: {"apps": [{ "name": "BSTAT", "script": &q ...

Using AngularJS to Nest ng-view within ng-repeat

I have a collection of items. Each item has buttons to display its details and comments within this ng-view section. It is necessary for the user to view all available product details on one page, for example. Below is the HTML list: <div ng-controll ...

What is the best way to run a lengthy task in Node.js by periodically checking the database for updates?

In my current setup, there is a routine that continuously checks the database for any pending work orders. Upon finding one, it needs to execute it promptly. The system can handle only one work order at a time, and these tasks may vary in duration from 5 s ...

Is there a way to retrieve data from both JSON and a file simultaneously?

I'm trying to use JavaScript fetch API to upload a photo message with text to Discord webhook. How can I upload both my JSON data and file? var discordWebHookBody = new FormData() discordWebHookBody.append("map", map) discordWebHookBody.appe ...

The Axios post request is mistakenly sending my data as the key with an empty value instead of sending the entire data object itself

I began by developing the frontend, but now I am looking to create the backend in order to establish a connection with a database. const express = require("express"); const bodyParser = require("body-parser"); const cors = require(" ...

Custom variables can be passed to subscription buttons through Paypal

I am currently working on finding a solution to passing custom variables when applying for a subscription for my created web service. The code on the front end that I have implemented so far is as follows: const createSubscription = (data, actions) => { ...

Unable to Click on Selenium Element

When a link is clicked on a website, the URL remains unchanged but a popup appears on the screen containing elements that can only be accessed after running driver.switchTo().defaultContent(). To access these elements, I have used a javascript executor com ...

JQuery fails to remove the "display:hidden" attribute

List of methods I attempted: Utilizing .removeClass and addClass functions Applying show() and hide() methods Modifying the CSS properties Initially, I confirmed that my script contains onLoad. Furthermore, all other elements are functioning correctly. D ...

Having difficulty launching a new window within an app built with Electron and Nexjs (Nextron)

Attempting to launch a (Nextjs-generated) page in a new window is causing an error message to appear: Uncaught ReferenceError: global is not defined Here is the full error: react-refresh.js?ts=1665849319975:10 Uncaught ReferenceError: global is not de ...

Is there a way to exclusively use ES6 to import jQuery from an npm package?

After installing jQuery using npm -install jquery, a node_modules folder was created in my project with the jQuery library inside. However, I encountered an error when trying to import it using ES6 import. I am looking for a solution that does not involve ...

There was an issue with the specified entry-point "auth0/angular-jwt" as it is missing required dependencies

I am currently working on an Angular project with the following versions: @angular-devkit/architect 0.901.1 @angular-devkit/core 9.1.1 @angular-devkit/schematics 9.1.1 @schematics/angular 9.1.1 @schematics/update 0.901.1 rx ...

Attempting to use insertAdjacentHTML on a null property results in an error

I keep encountering the same error repeatedly... Can someone please explain what's going wrong here and provide a hint? Error script.js:20 Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null at renderHTML (script.js:20) a ...

Unable to generate two tables

I have a dynamic table creation issue. The tables are meant to be created based on the user's input for the "super" value. For example, if the user inputs "2" for super, then it should create 2 tables. However, this is not happening as expected becaus ...