Retrieving the chosen option in AngularJS

Just diving into the world of Angular, I decided to create a simple demo involving dynamic select options. The goal is to add a new select based on the current selected value. However, I'm encountering an issue where I can't retrieve the selected value. Any assistance would be greatly appreciated.

Below is the HTML code:

<md-input-container ng-repeat="a in selects" class="md-block" style="margin-top:20px;">
      <label>{{a.label}}</label>
      <md-select required  ng-model="a.model" ng-change="callme()" flex="40">
        <md-option ng-model="a.model" ng-repeat="optionValue in a.options" ng-value="optionValue.option">
            {{optionValue.option}}
        </md-option>
      </md-select>
      <div class="errors" ng-messages="petApp.favoriteColor.$error">
            <div ng-message="required"> You need to select an option</div>
      </div>
  </md-input-container>

Now for the JS code:

$scope.selects = [{label:"Your Pet",model:"pet",options:[{option:"Cat"},{option:"Dog"},{option:"Guinea pig"}]}];

$scope.callme = function(){
  console.log($scope.pet);
  $scope.selects.push({label:"Your Pet",model:"pet",options:[{option:"Cat"},{option:"Dog"},{option:"Guinea pig"}]});
}

It seems that when I use $scope.pet, it returns undefined even though the model name is pet.

Answer №1

To make use of $scope.pet as your model, ensure to include it in the ng-model directive in this way:

(ng-model is where the value of the selection gets assigned).

<md-input-container ng-repeat="a in selects" class="md-block"  style="margin-top:20px;">
      <label>{{a.label}}</label>
      <md-select required  ng-model="pet" ng-change="callme()" flex="40">
        <md-option ng-repeat="optionValue in a.options" ng-value="optionValue.option">
            {{optionValue.option}}
        </md-option>
      </md-select>
      <div class="errors" ng-messages="petApp.favoriteColor.$error">
            <div ng-message="required"> You need to select an option</div>
      </div>
  </md-input-container>

Furthermore, ensure that you declare your $scope.pet variable before rendering the page. To pre-populate your dropdown, assign a value to $scope.pet like so... $scope.pet = "Cat";

Your JavaScript code should resemble this:

$scope.pet = ""; // or assign pet a value if desired

$scope.selects =  [{label:"Your Pet",model:"pet",options:[{option:"Cat"},{option:"Dog"},{option:"Guinea pig"}]}];

$scope.callme = function(){
  console.log($scope.pet);
  $scope.selects.push({label:"Your Pet",model:"pet",options:[{option:"Cat"},{option:"Dog"},{option:"Guinea pig"}]});
}

The current setup with a.model as your ng-model value results in Angular assigning the value to the "model" property of the $scope.selects objects. By inspecting the $scope.selects array (using Angular Batarang or a similar Chrome plugin), you'll find the selected value in the model property of one of the objects.

In cases requiring multiple selects and models, leverage the existing object's model property or similar, such as a.model in your ng-model, and pass the "index" of "a" in selects in ng-change.

<md-select required  ng-model="a.model" ng-change="callme($index)" flex="40">

So when your "callme" function is triggered, you can retrieve the selected value using the following approach:

$scope.callme = function(index){
  console.log($scope.selects[index].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

"Error encountered: Module not found - Issue resolving module" while using signrequest-client in Angular

I've been attempting to integrate the signRequest API into my angular application. To do so, I first installed the signrequest-client using the following command: npm install signrequest-client --save Following this installation, I included the Ja ...

The use of an expandableRowTemplate causing an angular reload through routing is essential for

I've been scouring the internet for a solution to the expandable grid conundrum. Every time I click on the grid, the expandable row triggers an angular reload through ui routing. Unfortunately, all the Plunker examples have their files in the same lo ...

Utilizing dependency injection within an Angular 1 TypeScript application

Seeking assistance with integrating angular-jwt with typescript in my angular1 project. The angular-jwt package was installed using the following command: typings install dt~angular-jwt --global The package is located in typings>globals>angular-jwt ...

Is it possible to use contenteditable along with ng-model within an ng-repeat loop?

My current dilemma involves using the ng-repeat directive to generate a list of span elements. Each span includes both the contenteditable attribute and the ng-model directive for two-way data binding. Initially, everything functions as expected until I a ...

Explore the functionality of the Enter key and search button with JavaScript

I have the following code that works perfectly when I click on the search button. However, I would like to know how I can also initiate a search using the enter key. Here is the code snippet: <script> function mySearch() { var text = document.g ...

Exclude items from AngularJS watch list

Is there a way to manually run a digest loop on specifically selected watches? Take, for example, the scenario where I need a directive that constantly displays the current time (including seconds), but without triggering the digest loop every second. One ...

Tips for managing a stored data reservoir with react-query

I am looking to develop a unique custom hook that can effectively manage a cache and fetch only new items. Here is the expected behavior: Upon initial request for [1, 2, 3, 4, 5], it should fetch all [1, 2, 3, 4, 5] as the cache is empty. If a request is ...

Issue with minifying AngularJS and TypeScript route configuration for safe minification

Currently, I have a package containing multiple js files that were created from typescript files. However, when I attempt to apply minification to the package, the webpage encounters errors. The error message displayed on the Chrome console is: Uncaug ...

Encountering a preflight error due to Access-Control-Allow-Headers restriction

I recently completed an AngularJS application where I successfully integrated the Twitch API. Here is the code snippet: return $http({ url: "https://api.twitch.tv/kraken/streams", method: "GET", params: { channel: channel, limit: ...

Creating a dynamic sidebar menu with clickable submenus through jQuery and CSS for a user-friendly experience

<div id="sidebar" class="sidebar"> <div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 100%;"> <div data-scrollbar="true" data-height="100%" data-init="true" style="overflow: hidden; width: a ...

retrieve data from the API response using a node request

I initiated an API request using the request method. Everything seems to be functioning properly, but I am encountering difficulty extracting the results from the response. The snippet of my code in question is as follows: app.get('/events/:query&a ...

Using Next Js for Google authentication with Strapi CMS

Recently, I've been working on implementing Google authentication in my Next.js and Strapi application. However, every time I attempt to do so, I encounter the following error: Error: This action with HTTP GET is not supported by NextAuth.js. The i ...

The digest string for the crypto.pbkdf2Sync function is malfunctioning

I've been working on revamping the authentication system for an old application that previously ran on node 4.5, but I keep encountering an error whenever I attempt to log in. TypeError [ERR_INVALID_ARG_TYPE]: The "digest" argument must be one of type ...

Guide on linking the backend and frontend to enable live chatting between multiple users using socket.io

Currently, I am using Mongoose to save chat conversations between registered users. However, the chats can only be retrieved by refreshing the page, which is not an ideal real-time solution. How can I implement socket.io to enable real-time communication a ...

Sending information from JavaScript to php within a single file

Every time I try to use getDate() in my php file, I notice that the time returned is consistently 5 hours behind the system time. To address this issue, I have implemented a JavaScript solution to retrieve the time from the system instead. Below is the cod ...

Issue with exporting Typescript React component

Despite searching for answers, none of the related questions have been helpful... My goal is to export React components from a TypeScript library that I plan to publish on npm. For testing purposes before publishing, I am utilizing npm link. The structu ...

Color of the border to be applied on only a

I've been experimenting with view's border style properties to achieve a dynamic partial coloring of a circular shape, but I'm having difficulty making it work. My goal is to create something like this: https://i.sstatic.net/Xb0l7.png http ...

Is your Firebase .push() function encountering errors when trying to update the database?

I am facing an issue with a component that checks if a user has already upvoted a post. The logic is such that if the user has upvoted a post before, they cannot upvote it again. However, if they haven't upvoted it yet, they should be able to do so. ...

Ways to verify and incorporate https:// in a URL for a MEAN Stack application

When extracting the URL from API data, my code looks like this: <div class="row copy-text"> <a href="{{copy.Url}}" target="_blank" style="text-decoration: underline !important;">{{copy.Title}}</a> </div> I am interested in ve ...

What is the best way to determine the width of a CSS-styled div element?

Is there a way to retrieve the width of a div element that is specified by the developer? For example, using $('body').width() in jQuery will provide the width in pixels, even if it was not explicitly set. I specifically need to access the width ...