Updating dropdown selection with ng-model in AngularJS

nameList includes [“Julia”, “Evan”, “Tomas”];

select ng-model=“names” ng-options=“x for x in nameList”

In my controller, I make a service api call to GetNameByID/{id}” and based on the id, I need to set the default value of the dropdown menu in the modal form.

For example, if a user clicks on ID 1, the dropdown should display Julia by default.

The issue arises within the service call when I try to initialize the model with $scope.names = data. Instead of selecting Julia, it adds an empty option at the top. Even though console.log(data) prints “Julia”, it shows as

<option value=“?”></option>

Any suggestions on how to resolve this problem?

Answer №1

If we take a look at an example in HTML, it would be like this:

<div ng-app ng-controller="MyCtrl">
    <select ng-model="names" ng-options="item for item in nameList">
    </select>

    <p>Selected : {{names}}</p>

    <button ng-click="Update(2)"> Update(1)</button> 
</div>

The controller includes a service call that will update the dropdown list based on the index.

function MyCtrl($scope) {
    $scope.names = "Julia"
    $scope.nameList =  ["Julia", "Evan", "Tomas"]; 

    $scope.Update = function(_value){ 
        $scope.names = $scope.nameList[ parseInt(_value)] ;
    }
}

To see this code in action, you can visit this jsfiddle link.

Answer №2

To set the initial value of a dropdown, you can simply utilize ng-init as shown below:

<select ng-model="names" ng-init="names = data[0]" ng-options="x for x in data">
    <option value="">Select</option>
</select>

The value inside [0] within data[0] represents the index of the array.

Answer №3

Below is a handy example demonstrating how to customize options:

In your HTML code:

<select ng-model="selectedName" ng-options="x for x in nameList"></select>

Within your JavaScript file:

app.controller('myCtrl', function($scope) {
var id = 1;

$scope.names = ["Julia", "Evan", "Tomas"];
$scope.selectedName = $scope.names[id-1];    <---- tweak the ID here.
});

Remember to subtract 1 from the ID since arrays are indexed starting from 0. Hope this meets your requirements.

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

Storing Data Property Value from an Item in Rendered List Using Vue: A Quick Guide

I'm currently working on implementing a follow button for list items in Vue. My approach involves extracting the value of a specific property from a list item and storing it in the data object. Then, I plan to utilize this value within a method to app ...

Alert for any shift in the main task at hand

As a beginner in mobile development, I kindly ask for some understanding if I overlook any obvious details. My main objective now is to find a way to monitor a foreground task on both iOS and Android. To elaborate, I want my program to perform the followi ...

Ways to recycle the table feature in angular2?

I am new to Angular2 framework and I am looking to efficiently reuse a single table component across my entire application. However, I am encountering challenges when it comes to displaying arrays in the table rows. How can I iterate through any type of ar ...

Tips on how to ensure that an onClick JS function only runs when radio buttons are selected

I have implemented the formslider library for a form on my website. In the demo, the slide transitions to the next set of questions based on a click event triggered by radio buttons (answers). However, when I attempted to include checkboxes for users to s ...

Tips for choosing elements based on the length of an array

When using an each function, I scan the DOM to find multiple elements with a specific className. Depending on the length of this ClassName, it will create an array that is either 2 or 4 elements long. I need to distinguish between these two types of elem ...

What is the best way to display recently added information?

I'm curious about why the newly added data isn't showing up in the template, even though it does appear when using console.log (check out ViewPost.vue). After adding a new post, this is the result: result.png. Does anyone know how to fix this? ...

Could it be that this is a mysterious foreign alphabet or a problem with the encoding?

I'm facing a strange bug with characters on my website and I can't seem to figure out what's causing it. A foreign writer submitted an article to me, and when I received it, the font was displaying oddly. After some investigation, I've ...

What is the best way to send a parameter from JavaScript to a UserControl?

Within my ASP.Net application, I have a UserControl named EmployeesUserControl that is displayed within a JQuery modal dialog. Prior to displaying the Employees, I need to provide a filter criteria indicating which entity the employee belongs to. My query ...

Combining edit and view functionalities in jqGrid form

I've been exploring the jqGrid wiki but I'm having trouble finding answers to a couple of things. It seems like it might be too customized. 1) Can jqGrid be configured to display all fields of a row when editing via form edit, but only make a fe ...

Halt the adhesion of the Bootstrap column when it hits the div section

I have a simple bootstrap row containing two columns: <div class="row"> <div class="col-xs-7"> <p>Walking together</p> </div> <div class="col-xs-5" id="stay"> <p>Joyful journey</p> </div ...

What occurs in the event of a server crash following the scheduling of a task using cron?

Imagine I set a task to take place at time t2 in the future, where t1 < t2 < t3 If the server crashes at time t1, will the scheduled task still run if the server is restarted before t2 (t1 < t < t2)? What happens if the server crashes at t1 a ...

What would be more efficient for designing a webpage - static HTML or static DOM Javascript?

My burning question of the day is: which loads faster, a web page designed from static html like this: <html> <head> <title>Web page</title> </head> <body> <p>Hi community</p> </bo ...

What is the best way to store chat messages in a React application?

My idea for a chat application using React involves saving chat messages in localStorage. Below is the code snippet that illustrates this functionality: const [textMessages, setTextMessages] = useState([]); const [textValue, setTextValue] = useState(' ...

Animating content to slide into view in the same direction using CSS transitions

My goal is to smoothly slide one of two 'pages', represented as <divs>, into view with a gentle transition that allows the user to see one page sliding out while the other slides in. Eventually, this transition will be triggered from the ba ...

Simulating service calls in Jest Tests for StencilJs

When testing my StencilJs application with Jest, I encountered an issue with mocking a service class method used in a component. The service class has only one function that prints text: The Component class: import {sayHello} from './helloworld-servi ...

Retrieve the selected option from the dropdown menu in the specified form

What should I do if I have numerous products and want users to be able to add new dropdown boxes dynamically? When the submit button is clicked, only the value of "category[]" within the form should be retrieved. https://i.stack.imgur.com/v1fnd.png Below ...

The ID of the jQuery droppable element cannot be found

Is there a way to retrieve the ID of a li element from a droppable function? Currently, when I try to do so, it returns undefined. Any suggestions on why this might be happening? The structure of each li element is as follows: <li class="ui-state-def ...

Ways to showcase HTML table in a four-column layout/grid

Delving into Dynamic HTML table creation, I'm currently using jquery for rendering purposes. At the moment, I am only displaying the table. The Goal I aim to segment my table into four columns or a grid structure Something akin to this: https://i. ...

Node Webkit: No visible content?

Recently, I decided to explore Node-Webkit and encountered an issue. Despite coding the script below, nothing seems to appear on the screen and the file I intended to create remains missing. Even after installing npm for fs and os modules, I still face no ...

C# - Implementing JavaScript Object manipulation in .NET Core

As I was browsing, I noticed many similar questions from years ago. Let's kick off this discussion with a simple JavaScript example showcasing how easy it is to modify, read, and write properties in objects using this language. Take a look at the cod ...