Using angularjs ng-option alongside ng-change

In my model, I have a structure that resembles the following:

{
    id: 1,
    country: {
        code: 'GB',
        name: ''
    }
}

While the country code is stored in the database, the name is missing. Another application requires the country name instead of the code... When editing this model, I provide users with a dropdown menu containing a list of countries with both code and name. I defined the ng-options attribute as follows:

ng-options="item.code as item.name for item in controller.countries"

This way, the country's name is pre-filled with the existing code. The problem arises when I attempt to set the name once a different country is selected. I attempted to achieve this using the following code:

ng-change="controller.setCodeAndName(controller.model.country, item)"

The corresponding method looks like this:

setCodeAndName: function (model, item) {
    console.log(item);
    model.code = item.value;
    model.fullName = item.description;
},

However, I encountered an issue because item was undefined. This occurred because the currently selected item was not being passed to the method. Does anyone have a solution to ensure that a country can be pre-populated based on the code alone, and upon selection, the name is added to the object?

Answer №1

Make sure to add an ngModel to the select element. It is recommended to use the entire object as the model assignment. Your select code should look like this:

<select
    ng-model="selectedItem"
    ng-options="item as item.name for item in controller.countries"
    ng-change="controller.setCodeAndName(selectedItem)"
</select>

Here is your method:

setCodeAndName: function (item) {
    console.log(item);
    model.code = item.value;
    model.fullName = item.description;
},

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: Symfony encountered an uncaught type mismatch

Seeking assistance with correcting an Uncaught TypeError related to the tinyMCE editor malfunctioning. https://i.sstatic.net/vM8D5.png I have attempted potential solutions such as: - updating the tinymce installation by replacing the older reference wi ...

Unable to watch an embedded YouTube video within an iframe on an Ionic app on an iOS device following the display of an ad through AdMob

I am currently working on an app using Ionic and have successfully integrated iframes to display YouTube content. Everything runs smoothly on the browser, but when I compile it for iOS, there seems to be a problem. After displaying an ad with admob, the if ...

Arrange an array by the occurrence rate of its elements within objects contained in another array, using Javascript

I found the explanation to be rather complex. Essentially, my goal is to iterate through each object in the 'objects' array, analyze the 'choice' values, tally the frequency of each letter, and then arrange the original arrays based on ...

Is there a way to easily generate multiple prints with just one click?

How can I make this iframe print multiple times when the Print button is clicked? The current code only prints once. Any suggestions would be greatly appreciated. Thank you! $("#printing").on('click',function(){ var printYesNo = ...

Tips on presenting an image from within an MP3 file within an image tag

Hello, I attempted to display the image retrieved from an mp3 file in an image tag using HTML and ReactJS. Here is the code snippet that I utilized. async getImageFromUploadedFile(framesRetrieved){ const imageArrayBufferRetrieved = framesRetrie ...

Change the position of a div by clicking a button using JavaScript

I have a div with an image that I want to move by clicking on a button within the same div. The reason for this is that clicking on the image itself allows it to move inside the div, but I want another element to control the movement of the entire div. He ...

Influencing location preferences in Google's place search

I'm currently implementing a Google Places search feature and I need to enable "Location Biasing" for the GCC countries (UAE, Saudi Arabia, Oman, Kuwait & Bahrain). My goal is to achieve the functionality described in the following link: https://deve ...

Initiate a $digest cycle externally

How can I ensure that $digest triggers when calling methods from outside Angular in an application where code is loaded and eval'd at runtime? Considering that these methods may also be called from within Angular, would it be better to expose a separa ...

Guide on showcasing an array element from a .js file into a paragraph on an .html document

I'm looking to create a JavaScript function that changes the text displayed every 7 days in the footer of an HTML file. The challenge I'm facing is figuring out how to dynamically update the text inside a paragraph tag in the HTML. myArray = [[i ...

Customizing the Mui Theme in a Unique Way

After generating an MUI component from Mui DatePicker, I encountered the following code: <span class="my-theme-MuiTypography-root my-theme-MuiTypography-caption my-theme-MuiDayCalendar-weekdayLabel css-1mln09i-MuiTypography-root-MuiDayCalendar-week ...

"Enhance search functionality by integrating live search results with clickable hyperlinks

I am currently working on implementing a live search feature in Laravel 7. Everything is functioning correctly, however, I am facing an issue where I am unable to add a (href a tag) to the result list. The results are being displayed in a select option usi ...

When using `this.array.find` within methods or computed properties in Vue, it sometimes returns

Within a component, I am receiving an array called approvalOptions from getters that contains a certain value I need to find. I have attempted the following methods: Using it within methods (read from ...mapGetters) as shown below methods: { approva ...

Utilizing ReactJS to display a new screen post-login using a form, extracting information from Express JSON

I am facing a challenge with updating the page on my SPA application after a successful login. I have successfully sent the form data to the API using a proxy, but now the API responds with a user_ID in JSON format. However, I'm struggling with making ...

Is it possible to swap the src of the Next.Js Image Component dynamically and incorporate animations in the

Is there a way to change the src of an image in Nextjs by using state and add animations like fadein and fadeout? I currently have it set up to change the image source when hovering over it. const [logoSrc, setLogoSrc] = useState("/logo.png"); <Image ...

Countdown Widget - Transform "0 Days" to "Today" with jQuery

I am currently working on a countdown page using the Keith Woods Countdown jQuery plugin which can be found at . Here is the code I have implemented so far: $(document).ready(function () { var segera = new Date(); segera = new Date(segera.getFullYear(), 2 ...

Is there a way to remove a portion of a string?

Looking to remove a section of a string using JavaScript? I attempted var sentence = "C:\mnt\c\User\Foo\Bar"; var updatedSentence = sentence.replace("mnt\c", ""); But the result was not as expected ...

Next.JS - What is the reason behind data fetching occurring on both the server and client side?

When I call a regular fetch function in the index.js component and then log the response to the console, something unexpected happens. Despite the fetch being inside the component function, the response is also logged on the server side: it shows up in the ...

Unable to establish a connection with the node at http://localhost:8545

Issues Encountered: I am having trouble with the Web3.min.js path in my system directory! The Web3.min.js file is being loaded from a folder in my browser. I have copied the web3.min.js file to the same folder where the index.html file is l ...

Ways to limit Javascript math results to two decimal points and erase previous output in one go

Working on a JavaScript multiplication task. The input provided is multiplied by 0.05. The JavaScript code successfully multiplies the input number by 0.05, but encounters some issues: The calculated value should be rounded to two decimal points. For ex ...

Ways to enable automatic scrolling of a page as the content expands (Utilizing collapsible elements)

For a recent project I've been working on, I decided to include 4 collapsible text boxes. However, I encountered an issue where opening content1 would expand and push down content2-4, requiring the user to manually scroll to view the remaining collaps ...