Eliminating blank options from an AngularJS select dropdown menu

I'm encountering an issue while attempting to populate a select drop-down with data using AngularJS ng-repeat directive. Upon page load, the drop-down displays an empty option. How can I eliminate this empty item from showing up? Here is the snippet of code:

    <html>
  <head>
  </head>
  <body ng-app="app">
    <div ng-controller="homeCtrl">
      <select ng-model="selected">
        <option ng-repeat="item in items" value="{{item.id}}">
          {{item.name}}
        </option>
      </select>
      <span>
        {{selected}}
      </span>
    </div>
  </body>
</html>

Below is the corresponding JS code:

var app = angular.module('app',[]);
            app.controller('homeCtrl',['$scope',function($scope){
                $scope.selected = 1;
                $scope.items=[
                    {name: 'harry111',id:1},
                    {name: 'rimmi',id:2}
                ];

            }]);

Feel free to check out the live DEMO

Answer №1

To set the default selected value, change $scope.selected = 1; to $scope.selected = "1";

var app = angular.module('app',[]);
app.controller('homeCtrl',['$scope',function($scope){
 $scope.selected = "1";
$scope.items=[
{name: 'harry111',id:1},
{name: 'rimmi',id:2}
];     
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
  <head>
  </head>
  <body ng-app="app">
    <div ng-controller="homeCtrl">
      <select ng-model="selected">
        <option ng-repeat="item in items" value="{{item.id}}">
          {{item.name}}
        </option>
      </select>
      <span>
        {{selected}}
      </span>
    </div>
  </body>
</html>

Answer №2

To properly populate the dropdown menu, remember to use ng-repeat on the <select> element. Here's an example:

<html>
  <head>
  </head>
  <body ng-app="app">
    <div ng-controller="homeCtrl">
      <select ng-model="selected" ng-options="value.id as value.name for (key,value) in items"></select>
      <span>
        {{selected}}
      </span>
    </div>
  </body>
</html>

To avoid adding a blank option in the select dropdown, make sure to follow this method. You can view a working example on CODEPEN.

Answer №3

Consider using ng-options instead,

 ng-options="value.id as value.name for (key,value) in items"

EXAMPLE

var app = angular.module('app',[]);
app.controller('homeCtrl',['$scope',function($scope){
  $scope.items=[
{name: 'harry111',id:1},
{name: 'rimmi',id:2}
];
   $scope.selected = $scope.items[0].id;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
  <head>
  </head>
  <body ng-app="app">
    <div ng-controller="homeCtrl">
     <select ng-model="selected" ng-options="value.id as value.name
                                           for (key,value) in items"
  ></select>
      <span>
        {{selected}}
      </span>
    </div>
  </body>
</html>

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

Neglecting to Execute Success Function After Retrieving Data from PageMethods Using Multiple Parameters in C#

I attempted to trigger my OnSuccess function, but it did not execute on the server. This is my code: function Get_Data(option , text){ //returns 'data', 'data', --not call OnSuccess-- PageMethods.BindSeries(option,text,OnSuccess); ...

Uh-oh! An unexpected type error occurred. It seems that the property 'paginator' cannot be set

I am developing a responsive table using Angular Material. To guide me, I found this helpful example here. Here is the progress I have made so far: HTML <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder ...

How can I retrieve an array of data from Firebase Firestore using React Native?

I have been working on fetching Array data from Firebase Firestore. The data is being fetched successfully, but it is all displaying together. Is there a way to fetch each piece of data one by one? Please refer to the image for a better understanding of ...

What is the process for extracting a single hashtag using the Twitter API with JSON in JavaScript?

Currently, I am utilizing the npm package 'twit' in conjunction with node js to interact with the Twitter API. My goal is to retrieve the hashtags used by a specific user in their most recent tweets. By employing the following code snippet, I ca ...

How to deactivate a text box within a form that is dynamically generated using Angular

I have encountered an issue with disabling the textbox inside my dynamic form in AngularJS after clicking a button. My code works perfectly fine for disabling textboxes outside the dynamic form, but when I try to target the ID of the textbox within the dyn ...

Adding a task to my database successfully through Postman integration

I'm having trouble implementing the code for my todo app using React. I am encountering an issue with adding a new todo to the database using the handleSubmit function. Oddly enough, it works fine when testing with Postman, but not when trying to inpu ...

Sending a `refresh` to a Context

I'm struggling to pass a refetch function from a useQuery() hook into a context in order to call it within the context. I've been facing issues with type mismatches, and sometimes the app crashes with an error saying that refetch() is not a funct ...

Ensure that the execution of the function is completed before moving on to the next iteration within a $.each loop

While I'm not an expert in JS or jQuery, I'm currently working on coding a chat application that requires the following functionality: Retrieve conversation list through an AJAX call Display the conversations on the left side of the webpage aft ...

Tips for selecting 'module' over 'main' in package.json

I have developed several npm modules and compiled them in two ways: commonJS (using exports.default =) and esm (using export default) In my package.json, I have specified the main file as index.cjs.js and the module file as index.esm.js. However, when ...

Identifying the unique parent component of a component within Angular

One of my components, named Com1, is imported into multiple other components. Within Com1, there is a button that triggers a function when clicked. In this function, I am trying to print out the parent component of the specific instance of Com1. How can I ...

Instructions on how to export an HTML table to Excel or PDF by including specific buttons using PHP or JavaScript

I created a table to display leave details of employees with sorting options from date to date. Now, I need to include buttons for exporting the data to Excel and PDF formats. Check out the code below: <form name="filter" method="POST"> <in ...

Challenges with splitting asynchronous code in NPM modules

Earlier, I posted a query on Stack Overflow I have recently established a local package within the main app's package.json: "contact-page": "file:local_modules/contact-page" The package.jsonmain and scripts sections for the contact module are confi ...

Angular directive for dynamic template inclusion

I am facing an issue while creating a directive that should automatically add tabs and their content. The problem I'm encountering is retrieving the content stored in partials/tabs/tab[x].html. In my code, I have defined a constant named AvailableTab ...

Material UI select field box not displaying the chosen option

After implementing a select component with Mui, I encountered an issue where although the selected option gets stored correctly in the defined state, it does not display within the select box itself. Below is the JSON object used: const DataExample = [ { ...

A step-by-step guide on using Jquery to fade out a single button

My array of options is laid out in a row of buttons: <div class="console_row1"> <button class="button">TOFU</button> <button class="button">BEANS</button> <button class="button">RIC ...

Present the array elements in a format that allows the user to easily choose an option and explore the content

I'm currently working on a project where users will take a Computer Based Test and be graded on a selected subject. I have a database set up with questions and multiple choice options. My goal is to display the questions in a way that allows users to ...

Error encountered while downloading file from S3 on NextJs due to network issue

I have encountered a network error while trying to download a file from Amazon S3. Despite configuring my Amazon config file correctly and using the S3.getObjectURl() method for the download, it still fails. Below is the snippet of my code: const AWSDownlo ...

Is it possible to create CLI commands directly from an AngularJS controller?

While attempting to integrate CLI/terminal commands in my AngularJS controller using the child-process module, I encountered some obstacles. Below is the code snippet for my service: listFiles.js: 'use strict' var exec = require('child_pro ...

I am able to access the JSON file from the URL without any issues, but for some reason, I am unable to fetch it using $

(function(){ $(document).ready(function(){ $.getJSON('http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol=AAPL&callback=?', function(){console.log("function was run");}); }); }()) I recently delved into working with APIs. Ho ...

An object-c alternative to encodeURIComponent

Having difficulty finding information on this through a search engine. Is there a similar method in Objective-C for encoding URI components? http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp This is a common task, but I am unable to locate any ...