"Using AngularJS to display a blank option as preselected in an ng-option

Having an issue with displaying a preselected value as the selected option in my select element. Check out the code below:

<select ng-model="data.company" ng-options="company as company.name for company in companies"></select>


$scope.companies =[{
    id:1,
    name:"Company 1"
},
{
    id:2,
    name:"Company 2"
}];

$scope.data = {
    company:{
        id:2,
        name:"Company 2"
    }
}

The problem I'm facing is that when I enter the section, the select shows me a blank option by default instead of "Company 2". What am I doing wrong?

Answer №1

If you want to bind an object directly to the ng-model, using the track by expression is necessary in this scenario. When you assign an object to data.company (ng-model), track by expression compares the company.id within that ng-model with the id of each element in companies. If there's a match, it will automatically pre-select that input.

Example:

<select ng-model="data.company" 
   ng-options="company as company.name for company in companies track by company.id">
</select>

View Demo Plunkr

Answer №2

One possible solution is to utilize the ng-init directive

<select ng-init="data.company= companies[0]" 
        ng-model="data.company" 
        ng-options="company as company.name for company in companies"></select>

Answer №3

Consider using this approach

 <select ng-model="data.organization" ng-options="org.name for org in organizations"></select>

  $scope.data = {
      organization: $scope.organizations[1];
  };

Ensure that the value displayed in the dropdown corresponds to the organization's name, with the object being stored as the organization itself.

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

Utilizing Cordova for Windows 8.1 in Visual Studio 2015 for external image retrieval and insertion into img tag

I am encountering an issue with displaying external images in a Cordova app. While the DOM is functioning correctly, the images are failing to load. I am specifically trying to resolve this for Windows 8.1 only. In my Cordova project for JavaScript, I have ...

Managing Modules at Runtime in Electron and Typescript: Best Practices to Ensure Smooth Operation

Creating an Electron application using Typescript has led to a specific project structure upon compilation: dist html index.html scripts ApplicationView.js ApplicationViewModel.js The index.html file includes the following script tag: <script ...

Using Angular.js Select with ngOptions to group options under a specific label

Exploring the wonders of Angular.js, I have a query regarding ngOptions: Can optgroups be labeled? Imagine two entities - cars and garages. cars = [ {"id": 1, "name": "Diablo", "color": "red", "garageId": 1}, {"id": 2, "name": "Countach", "color" ...

Utilizing the Power of Mui Datatable to Enhance User Experience with Repeatable Edit and Delete

Hey Everyone, I'm currently trying to implement edit and delete buttons in ReactJS using Mui Datatable. However, I am facing a recurring issue due to the Map function since I am relatively new to ReactJS. Below is my image and code snippet: Here is a ...

An error message is displayed when attempting to retrieve a json response

After implementing my flask app, I noticed that the following code snippet is being returned: return json.dumps({'status': 'OK','url': 'www.blahg.com'}) Upon inspecting my javascript code, I found it to be structur ...

What is the best way to create a Snap.svg map using AngularJS?

I am in the process of creating a web interface for an online board game. My goal is to load a Snap.svg map using Snap.load asynchronously. Once the map is loaded, I intend to attach a watch to a scope property and apply colors to the map based on that pr ...

What is the best way to include a character within a DIV element using ng-style?

After experimenting with NG-STYLE, it seems to be functioning properly. However, I am facing a challenge when trying to add the percentage symbol (%) after retrieving data from the CONTROLLER. <div class="progress progress-mini"> <div ng-style= ...

Executing JavaScript following an Ajax request

I am faced with a situation where my HTML file utilizes a function for loading another PHP file using Ajax: function LoadContent(n,func) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xm ...

collection of assurances and the Promise.all() method

Currently, I am dealing with an array of Promises that looks like this: let promisesArray = [ service1.load('blabla'), service2.load(), // throws an error ]; My goal is to execute all these Promises and handle any errors that occur, as ...

Moving specified data from one interactive table to another interactive table

In my setup, there are two tables - one for products and another for customers: <table cellpadding="0" cellspacing="0"> <thead> <tr> <th>Product Code</th> </tr> </thead> ...

Ways to determine the success of $wpdb->query and retrieve the outcome

Currently, I am in the process of developing a WordPress website, I have implemented a form that allows users to make modifications and update the database: Below is the HTML/PHP code snippet: echo '<form class="form-verifdoc" target=&q ...

How to Retrieve OnLoad HTML/DOM Content for an HTML Page using PHP

I am interested in retrieving the initial HTML content of a web page specified by its URI. Ignoring error handling and assuming the HTML is static, here is a simple function: function GetDisplayedHTML($uri) { return file_get_contents($uri); } For stat ...

Unable to assign values to textarea and checkbox in MVC5

I am currently facing an issue with setting values in JavaScript + jQuery in MVC 5 for textareas and checkboxes. Here is the JavaScript code I am using: document.getElementById("UpdatetxtDescription").value = "abc"; document.getElementById("Upda ...

Error arises when uploading csv files to Node.js with Multer due to an unexpected field presence

I'm currently working on implementing a file upload feature with the use of Node.js, Vue, and Multer. Below is the Vue.js front-end code: export default { data(){ return{ selected: "How do you want to input the data?", options: [ ...

Sinon respects my intern functions during testing in ExpressJS

At the moment, I am working on incorporating sinon stubs into my express routes. However, I am facing an issue where my functions are not being replaced as expected. I would like my test to send a request to my login route and have it call a fake function ...

Continue running the remaining part of the function once the asynchronous function has completed its execution

To obtain the last 4 digits of a payment using Stripe, I need to execute an async function that contains another async function. Once these functions are resolved, I aim to update the database with the last four digits. It is crucial to ensure that the dat ...

TinyMCE version 5.x - Stand out with a specific selection in a personalized drop-down navigation bar

In my customized TinyMCE 5.x dropdown menu, there are 3 options that adjust the width of the editor. I am looking for a way to indicate the currently selected option, but I am unable to interact with the menu items once they are initialized. It seems like ...

Biscuits within a smartphone application

Currently, I am in the process of developing a Hybrid mobile app using the Ionic Framework. In order to store some data within the DOM (specifically Username and Email) on a single view with minimal storage requirements, I have decided to utilize cookies- ...

Is the existence of the file also verified by JavaScript's realpathSync() function?

I want to utilize node.js FileSystem realpathSync() to find the actual path of a file. Does realpathSync() also verify if the file exists? Would this code be sufficient: try { res = fs.realpathSync(path); } catch (err) { ...

Guide on implementing a progress bar for file uploads with JavaScript and AJAX request

I am looking to implement a progress bar in my file uploader. Below is the ajax call I have set up for both file upload and progress tracking. $(function() { $('button[type=button]').click(function(e) { e.preventDefault(); ...