Exploring Angularjs: Retrieving the value of a selected optgroup

When using my application, I need to extract the selected optgroup value from a dropdown menu.

Here is the sample code:

HTML:

<select ng-model='theModel' ng-change="display(theModel)" >
    <optgroup ng-repeat='group in collection' label="{{group.Name}}">
    <option ng-repeat='veh in group.Fields'>{{veh.Name}}</option>
    </optgroup>
</select>

Controller:

$scope.display = function(name) {
    alert(name); // To obtain the selected value and the optgroup value
}

VIEW DEMO APP

DESIRED OUTPUT: I want to show the selected optgroup value. For example, if I select Field1 under Collection 1, I should see Collection1.Field1 displayed.

Answer №1

After making some updates, the options now hold references to both the group and values. If the values in groups were unique, a value to group map in the controller variable could have been used to retrieve data easily. However, since the same values exist in multiple groups, I have included a reference to the group in the option values.

The select box now displays the desired text and the values of options have been updated to maintain references to the groups. This way, both pieces of information are readily available.

Check out the Updated Plunkr here: https://plnkr.co/edit/zvNcdDe0kmMJ1R67hOkK?p=preview

Controller:

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

app.controller("dobController", ["$scope", "$http",
  function($scope, $http) {
    $http.get('test.json').then(function(response) {
      $scope.collection = response.data.Collections;
      console.log(response);
    });

    $scope.matches = [];

    $scope.display = function(name) {

       alert("controller:"+name.split("::")[0]+" and value ::"+name.split("::")[1] );
    }

  }
]);

HTML:

<select ng-model='theModel' ng-change="display(theModel)">
    <optgroup ng-repeat='group in collection' label="{{group.Name}}">
    <option ng-repeat='veh in group.Fields' value='{{group.Name}}::{{veh.Name}}'>{{veh.Name}}</option>
    </optgroup>
    </select>

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

Is there a way to define the width of an element within the display:flex property in CSS?

Could you please review the following: https://codepen.io/sir-j/pen/dyRVrPb I am encountering an issue where setting the input [type=range] to 500px doesn't seem to make a difference from 100px, 500px, or 800px. This leads me to believe that display ...

Can data be presented in AngularJS without the use of scope variables?

I have a method: <span ng-init="getJobApplicantsList(jobId)">(number should be display here)</span> Is there a way to display the data without having to store it in a scope variable? I need to use this method in many places. This is my cont ...

Getting the desired value from a CreatableSelect in React can be achieved by following these steps:

I have a form that includes a React library component called React Select. I'm struggling to retrieve the target value of this input field. Here's my code snippet: # CreatableSelect tag <CreatableSelect className={Astyle.selectInput} i ...

Is there a way to download and store the PDF file created using html2pdf in Node.js on my local machine?

I have successfully generated a PDF using html2pdf, but now I want to either send it to my server in Node.js or save it directly onto the server. Currently, the PDF is downloaded at the client's specified path, but I also need a copy saved on my serve ...

Having issues with $_POST not retrieving values from .post

Below is the javascript snippet that I have written: function submitForm() { var name = document.getElementsByName('name').value ,email = document.getElementsByName('email').value ,subject = document.getElementsBy ...

The appropriate use of spacing after text in the context of HTML and

Why is it that when I add padding or margin, no extra space is created after the text? Here is the output: https://i.sstatic.net/1MwjE.png I have tried adding padding and margin after the Stay Tuned text, but it seems to be not working. Any insights on ...

Connecting JavaScript and HTML in EclipseWould you like to know how to link

After completing the Rock Paper Scissors exercise on Codecademy, I wanted to transfer it to my Eclipse IDE. The code worked perfectly on the Codecademy platform, so I copied everything and created a .js workspace in Eclipse to paste it there. Now, my ques ...

The use of p-message in Angular's PrimeNg library is not permitted

Hey there, I'm having a bit of trouble with the p-message Tag in Angular. I believe I've imported it correctly as shown below. import { MessageModule } from 'primeng/message'; imports: [ .... MessageModule, ... In the ...

HTML5 failing to load button

<!DOCTYPE html> <html> <head> <title>Greetings Earthlings</title> <script src="HelloWorld.js" /> </head> <body> <button onclick ="pressButton()" >Press Me!</button> ...

Adding properties with strings as identifiers to classes in TypeScript: A step-by-step guide

I am working with a list of string values that represent the identifiers of fields I need to add to a class. For instance: Consider the following string array: let stringArr = ['player1score', 'player2score', 'player3score' ...

What reasons underlie the existence of various methods for importing Modules in JavaScript?

I'm confused about the distinctions when it comes to importing a JavaScript module in various ways such as: CommonJS ES5 ES6 NodeJS Typescript What is the reason for having multiple methods of importing JavaScript modules? Is the concept of a "modu ...

Utilizing React Router to dynamically render components based on JSON object data

My current challenge involves rendering React components based on the component names in a JSON file I've created. Specifically, I want to render the TestSection component within the context of my Route component. To achieve this, I am utilizing the ...

What steps can be taken to customize this code in order to develop a dictation application?

Currently, I have a code that functions by comparing two strings: str2 (which represents user input) and str1 (our reference string). The purpose is to determine whether any words in str2 are spelled correctly or incorrectly. So far, the code works well. H ...

The functionality of the MVC jQuery grid is currently malfunctioning

Recently, I attempted to integrate a jQuery grid plugin from gijgo.com into my MVC application. Following the instructions provided on c-sharpcorner and/or codeproject meticulously, however, upon running the application, I encountered a troubling JavaScrip ...

Problems with Ajax calls are preventing Internet Explorer9 and Internet Explorer10 from functioning properly

I am facing an issue with displaying item pages using Ajax. The function works perfectly in Chrome, but not in Internet Explorer. <script type="text/javascript"> function obtainInfo(str) { if (str=="") { document. ...

Adding an extra element to the <MuiThemeProvider /> causes the page to display as blank with no error notifications

After incorporating Material UI into my Meteor application via npm install --save material ui I successfully implemented the <Header /> component in my app.js file. However, when I try to add additional components, such as localhost:3000, all I see ...

What are the steps to integrate dynamic data into chartjs?

Can you assist me in understanding how to dynamically populate Chartjs with data from a json file? Specifically, I am looking to dynamically fill the labels and data fields. Sample JSON File <<< [ { "EFICAZ_TAB_ITEM_ID":1, " ...

Troubleshooting undefined results when dynamically loading JSON data with $scope values in AngularJS

My input field is connected to the ng-model as shown below. <div ng-app="myApp" ng-controller="GlobalCtrl"> <input type="text" ng-model="FirstName"> {{FirstName}} </div> In my controller, console.log $scope.FirstName shows m ...

The values returned by the Node.js API can vary for identical requests

I am currently learning how to use Node.js + Express in order to create a REST API. Within this API, I have implemented the following method: apiRouter.route('/training/session/byId/:id_session') // ===== GET ======= .get(function(req, res ...

Why do I keep receiving the unprocessed JSON object instead of the expected partial view output?

Upon submitting my form, instead of displaying the testing alerts I have set up, the page is redirected to a new window where the raw JSON object is shown. My assumption is that this occurrence is related to returning a JSON result from the controller. How ...