What is the best way to retrieve the value key on click in AngularJS?

When a button is clicked, I want to retrieve the key value of the selected item from an md-select dropdown list that is bound with data using ng-repeat.

Below is my JavaScript code:

 $scope.checklist= [{ "val": 1, "txt": "one" }, { "val": 2, 
"txt": "two" }, { "val": 3, "txt": "three" }, { "val": 4, 
"txt": "four" }, { "val": 5, "txt": "five" }, { "val": 6, 
"txt": "six" }, { "val": 7, "txt": "seven" }, { "val": 8, 
"txt": "eight" }, { "val": 9, "txt": "nine" }, { "val": 10, 
"txt": "ten" }, { "val": 11, "txt": "eleven" }];

  $scope.searchTerm;
  $scope.clearSearchTerm = function () {
      $scope.searchTerm = '';
  };
 $scope.getDropdwnSelectedValue = function (val) {
       alert(val);
  }

Here is the HTML code:

<div layout="row">
        <md-input-container>

            <md-select ng-model="selected.key" md-on-close="clearSearchTerm()" multiple="" style="width:300px;">
                <md-select-header>
                    <input ng-model="searchTerm" type="search" placeholder="Search for ..">
                </md-select-header>
                <md-optgroup label="list">
                    <md-option ng-value="chkLst.txt" ng-repeat="chkLst in checklist|
          filter:searchTerm" >{{chkLst.txt}}</md-option>
                </md-optgroup>
            </md-select>
        </md-input-container>
    </div>
<md-button class="md-raised md-primary" ng-click="getDropdwnSelectedValue (selected)">Get Value</md-button>

Answer №1

You made an error in the

ng-repeat="chkLstin checklist | ..."
line - it should actually be chkLst in checklist | .... Additionally, there's no need to create a function call to check your values while developing. Simply include
<pre>{{selected.key}}</pre>
in your HTML to easily see if you are getting the value in ng-model.

For reference, here is a working codepen example

Answer №2

To obtain the chosen value, ensure that your scope variable is set correctly. Begin by initializing the scope variable with $scope.choice = {}. You can then access the selected value using $scope.choice.option as it corresponds to your ng-model

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

Having difficulty in dynamically loading an image from an API's URL in Angular

In the title, I mentioned that I am utilizing a free API to display cryptocurrency news for my practice project. Everything seems to be working fine except for displaying the images in card view. I will share my code here, so if you have any suggestions on ...

Having trouble bypassing custom points on the reactive gauge speedometer

My current project involves utilizing the npm package react-d3-speedometer to create a custom points-based gauge. The issue I am facing is that while the package works properly with values from 0 to 1000 when passed to the customSegmentValues property, it ...

How do I activate Angular/Backbone/jQuery intellisense in VSCode for a project that does not have a package.json file?

Currently, I find myself at a standstill trying to enable code autocompletion for popular libraries like BackboneJS, Angular, and jQuery. Unfortunately, the recommended method provided by the VS Code official documentation is not accessible to me (which in ...

Error message encountered: React hydrate TypeError - the function __webpack_require_.i(...) is not recognized as a

I encountered a webpack TypeError while attempting to use hydrate() in my index.js file. Strangely, the error does not appear when I use ReactDOM.render() instead of hydrate. My intention behind using hydrate was for server-side rendering. src/index.js i ...

What is the best method to extract an array of values or rows from my grid layout?

Looking for a way to convert my CSS-grid into a CSV format. I came across a helpful thread outlining how to structure the data in an array: How to export JavaScript array info to csv (on client side)?. Is there a method to extract all the div values in th ...

Looking for assistance in resolving the error message: 'state' is not defined no-undef

I'm having some trouble adding a navbar to one of my projects as I keep encountering a failed to compile error. "Line 7:5: 'state' is not defined no-undef Line 9:5: 'handleClick' is not defined no-undef" import React, { ...

Span wrapped in a hover effect

I am facing an issue with hover options... What I am looking for is a text in a circle Finally, I achieved the desired look using csswrap Next, I added some jQuery to insert links into all spans with the same class Everything is working fine, except fo ...

The Mapbox JS SDK stylesheet leads to the sudden disappearance of the map

Incorporating the Mapbox JavaScript SDK into my VueJS app has been successful in displaying a map. Now, I am looking to enhance it by adding markers. According to this page, importing a CSS stylesheet is necessary for markers to function properly. I have a ...

methods for efficient set computations

I have a collection of sets in the format (a,b) which are as follows: (2,4) (1,3) (4,5) (1,2) If I am given a pair like <2,1>, I want to identify all sets in the collection where 2 or 1 is the first element. In this case, it would be (2,4), (1,3), ...

Is it possible to include two of these on a single page with unique variables? (Using JQuery)

I am looking to create two similar pages, each with different percentages. However, when I try modifying the JS or changing class/ID names, it keeps pulling data from the first SPAN element. http://jsfiddle.net/K62Ra/ <div class="container"> <di ...

Guide on executing a service call using an Angular-UI modal object

I have recently decided to switch to an Angular-UI modal and I'm facing some confusion about how to execute a $http get call and retrieve the results. Previously, I was using a different Angular modal with the existing code. While I understand how it ...

Troubleshooting Automatic Scrolling Problems in React Virtualized

In my project utilizing react-virtualized v-9.21.2 to showcase a list, a problem arises when adding a new item. I employ a method of clearing the cache and updating the listKey to enable auto resizing the height. However, this results in an undesired behav ...

Subfolder is not generating the batch file

I need help troubleshooting this code. I created a temporary folder in the C drive, but for some reason the batch file isn't getting created. Can anyone provide some suggestions or insights? var sText, s; var fso = new ActiveXObject("Scripting.Fi ...

Top method for transferring server (C# / Razor) data to an AngularJS application

In our use of DNN, we often encounter the need to pass specific context values (such as page id or module-on-page-id) into an AngularJS application. While we have established our own conventions for achieving this, we are interested in hearing about how ot ...

The value of React state may be unpredictable, even if it appears to be defined on the

<li className="field-title">Role: </li> {console.log(this.state.userData.roles)} {this.state.userData.roles.map((role) => { return ( <li>{role.name}</li> ) })} Even though when I console log the state ...

Instead of relying on the scope within the controller, opt to delete Todo data within the service layer

My code snippet is as follows: angular.module("todoListApp", []) .controller('mainCtrl', function($scope, dataService){ /* updated */ dataService.getTodos(function(response){ console.log(response.data); $scope.todos = response.data; }) ...

comparing caching with jquery deferred against promise

Currently, I have implemented code using jQuery Deferred and ajax to fetch data from a remote API, store it in localStorage, and retrieve it from there. However, this code has a bug where it doesn't display the data properly the first time it runs (re ...

Guide to integrating a Custom Font into live data on a PDF file with the help of jsPDF

I recently successfully converted a dynamic webpage to PDF using jsPDF and now I'm looking to customize the font family of the PDF document. Is there an option for this in jsPDF? Please advise, thank you! Here is my code snippet: <div id="#p ...

The Angular UI dialog promise is triggered only when the dialog is reopened

Within the controller that triggers the dialog, I have: $scope.openDialog = function () { var options = dialogOptionsFactory.build('/my/route/file.html', 'ChildController'); var d = $dialog.dialog(options); d.open().then(fu ...

Employ React Hooks for modifying the class names of elements and their related siblings

I have a function component in React hooks that I am working on. The goal is to change the className to 'active' when any element in the list is clicked, and remove the className from the other elements. const SideBar = () =>{ const [active ...