Choose the initial selection from a dropdown menu using AngularJS

I am facing a minor issue where I want the first element in my select dropdown to be displayed properly rather than just a blank space.

Below is the code snippet I am currently working with:

<select style="border-radius: 4px;" class="form-control" ng-model="select" ng-init="somethingHere = option[1]" id="sel1">
    <option ng-repeat="option in dateHeureAdd track by option.value" value="{{option.value}}">{{option.heure}}</option>
</select>

In the above code, I have defined an array called "dateHeureAdd" which contains time values for selection. However, the initial display does not show any default value or placeholder at the beginning of the dropdown list.

$scope.dateHeureAdd = [
    {value: '8', heure: '08:00'},
    {value: '9', heure: '09:00'},
    {value: '10', heure: '10:00'},
    {value: '11', heure: '11:00'},
    {value: '12', heure: '12:00'},
    {value: '13', heure: '13:00'},
    {value: '14', heure: '14:00'},
    {value: '15', heure: '15:00'},
    {value: '16', heure: '16:00'},
    {value: '17', heure: '17:00'}
]

If you would like to view the functionality, please visit the following Plunker link:

http://plnkr.co/edit/aDUGvrvJjszq07Sjh0TI?p=preview

Your assistance with this matter is greatly appreciated. Thank you!

Answer №1

One useful directive for handling options in AngularJS is ng-options. Additionally, you can reference the name of ng-module and set its default value.

Check out this functional solution: http://plnkr.co/edit/eHMoEqVxTv5QQh12FWv1?p=preview

Index.html:

<!doctype html>
<html ng-app="ui.bootstrap.demo">

<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
  <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.js"></script>

  <script src="script.js"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
  </br>
  <div ng-controller="Ctrl">
    <select class="form-control" ng-model="mySelect" ng-options="date as date.heure for date in dates track by date.value">

    </select>
  </div>
</body>

</html>

script.js:

angular.module('ui.bootstrap.demo', ['ui.router','ngAnimate', 'ngSanitize', 'ui.bootstrap']);



angular.module('ui.bootstrap.demo', [])
  .controller('Ctrl',[ '$scope', function ($scope) {
  $scope.dates = [
    {value: '8', heure: '08:00'},
    {value: '9', heure: '09:00'},
    {value: '10', heure: '10:00'},
    {value: '11', heure: '11:00'},
    {value: '12', heure: '12:00'},
    {value: '13', heure: '13:00'},
    {value: '14', heure: '14:00'},
    {value: '15', heure: '15:00'},
    {value: '16', heure: '16:00'},
    {value: '17', heure: '17:00'}]

  $scope.mySelect = $scope.dates[0];
}]);

Answer №2

Your approach to initializing your select value was incorrect; instead of using the alias in ng-repeat, you should use the original array's name.

 ng-init="somethingHere = option[1]"

change it to

  ng-init="somethingHere = dateHeureAdd[1].value"

Furthermore, make sure to assign the ng-model of the select correctly, as it was different in your particular case.

Updated Example

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

Issues with Gulp and Browser Sync integration

Encountering errors while running Gulp with Browser Sync in Chrome: NonESPMessageInterface --- nonEspMessageInterface.js:8 TypeError: Cannot read property 'insertBefore' of null --- angular.js:13708 Checklist message was invalid, from origin # ...

Managing multiple sets of radio buttons using the useState hook

Within my renderUpgrades-function, I handle the options of an item by including them in radio-button-groups. Each item has multiple options and each option has its own radio-button-group. Typically, a radio-button-group can be managed using useState, wit ...

Develop a feature within a standard plugin that allows users to add, remove, or refresh content easily

I have developed a simple plugin that builds tables: ; (function ($, window, document, undefined) { // Define the plugin name and default options var pluginName = "tableBuilder", defaults = { }; // Plugin constructor func ...

Unable to import a text file using a semicolon as delimiter in d3

I'm just starting to learn JavaScript and the D3 library. I recently explored the "d3-fetch" module (available at https://github.com/d3/d3-fetch) and the d3.dsv command API (find it here: https://github.com/d3/d3-dsv). However, I am struggling to unde ...

Troubleshooting a JQuery AJAX Autocomplete problem involving PHP and MySQL

I am facing an issue with my autocomplete feature. It is functioning properly on one of my pages, but not on this particular page. Even though the correct number of entries is being retrieved, they all appear to be "blank" or are displayed in black text th ...

The form created using jQuery is not submitting correctly because the PHP $_FILES array is empty

Creating an HTML form dynamically in jQuery and submitting the form data via Ajax to 'add_sw.php' for processing is my current challenge. However, I have encountered an issue where the PHP script cannot access the PHP $_FILES variable as it turn ...

Three.js tutorial: Rotating items on each axis individually

Looking to create an interactive 3D item that users can rotate with their mouse freely? I experimented with using three quaternions, one for each axis, and then multiplying them together to determine the final position of the item. // Initializing xQuat, y ...

Style the date using moment

All languages had a question like this except for JavaScript. I am trying to determine, based on the variable "day," whether it represents today, tomorrow, or any other day. ...

Get a compressed folder from jszip containing a PDF file that is either empty or blank

I'm facing a challenge with my Vue app where I need to compress a group of PDF files in a folder using JSZip. While testing with just one file, the zip downloads successfully but when I try to open the PDF file inside it, the content appears blank. I ...

The isolate scope variable is becoming undefined within the link function

When working with a directive that takes a data object and a function in its isolate scope, I encountered an issue. Inside the link function, I declared a method to be triggered on a button click event. The problem is that while the value passed to the me ...

What is the best way to organize columns on the front end?

A table needs to be displayed on the front end with the following code snippet: <logic:present name="searchStudent"> <table class=" tblSearchResult" border="1" cellspacing="0" cellpadding="0"&g ...

transmit information to a PHP script

I am facing an issue while trying to transmit data to a PHP file. Below is the code I've written: App.js: .controller('sign_up', function ($scope, $http) { $scope.login = function () { var request = $http({ met ...

The Javascript calculation function fails to execute proper calculations

I have been facing immense frustration while working on a project lately. The project involves creating a unique Webpage that can calculate the total cost for users based on their selections of radio buttons and check boxes. Assuming that all other functi ...

What could be causing my input to not activate my function?

I am having issues with my input buttons not triggering my functions. Can anyone provide some insight into this problem? <div id="windowBar"> <h3>Imagine you were a superhero...</h3> <input id="WindowClose" type="button" onclick=" ...

Grab the table headings from an HTML table and store them in variables after accessing the DOM

Looking to modify the structure of the DOM. Wanting to display table content using paragraphs instead. To achieve this, I need to extract data from each row in the table. How can I accomplish this task? <table style="width:300px"> <tr> ...

The 8 x 8 grid I am constructing is functional, however, the issue lies in the fact that the first line only begins with a single # symbol

I am attempting to create an 8 x 8 grid. It's coming together, but the issue is that the first line only starts with one # sign. function print(msg) { console.log(msg); return msg; } let result = ""; for(let i=1; i<=8; i++) { result += ...

tips on setting the time format in dimple.js

Trying to create a multi-line graph using dimple.js based on some sample code. I have flattened my JSON into an array and thought I had the code down, but I'm stuck. I am including these 2 libraries (using cloudflare dimple for security reasons): &l ...

Vue3 is struggling to apply dynamic styling exclusively to certain buttons

Currently, I am diving into the world of vue and facing a challenge in styling buttons dynamically when clicked individually. These buttons serve as filters for a list of products, and my goal is to apply one style when the filter is 'on' and ano ...

Discover how to use jQuery to add CSS styles to every span element on a

I'm currently using JavaScript and jQuery to create a tree structure in ASP.NET MVC. There's an 'add' button that will add siblings and child nodes at the same level. To determine the appropriate action, I have implemented the followi ...

Swipe to modify Array

Currently, I am in the process of developing an application that features a Swipe card interface using both AngularJS and the Ionic framework. The functionality of this app will be similar to the one found at . When swiping to accept a card, I want the ar ...