AngularJS: default option not being selected in dropdown menus

I need assistance with a dropdown list issue. See the code snippet below:

My Controller

(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };

    $scope.data.model=1;

 }]);
})(window.angular);

My UI

<body ng-app="ngrepeatSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>
</body>

Check out this demo. Despite setting $scope.data.model to 1, the dropdown list appears blank.

I've attempted various solutions without success. Any help is appreciated. Thank you and excuse my language skills.

Edit Note : I previously tried following this guide, but the issue persists.

Answer №1

Your object IDs are string while your data.model is number.

Update your data type to be consistent and it will function correctly.

(function(angular) {
  'use strict';
angular.module('ngrepeatSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ]
    };
    
    $scope.data.model='1';
    
 }]);
})(window.angular);
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8>
  <title>Example - example-select-ngrepeat-production</title>
  

  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  <script src="app.js"></script>
  

  
</head>
<body ng-app="ngrepeatSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>
</body>
</html>

Refer to the example on AngularJS official documentation

https://i.stack.imgur.com/MOlcn.png

Answer №2

Modify the select value using ng-value directive

<select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  <option ng-repeat="choice in data.availableOptions" ng-value="{{choice.id}}">{{choice.name}}</option>
</select>

Check out the updated Plunker here

Answer №3

It is highly recommended in angular to utilize ng-options instead of ng-repeat for select dropdowns. To set a default selection, the ng-model value must be assigned in the controller as the option object itself, ensuring that the data type matches exactly.

For example:

$scope.data.model = $scope.data.availableOptions[0];

Here is an functional illustration responding to your query.

(function (angular) {
    'use strict';
    angular.module('ngrepeatSelect', [])
        .controller('ExampleController', ['$scope', function ($scope) {
            $scope.data = {
                model: null,
                availableOptions: [{id: '1', name: 'Option A'},
                    {id: '2',name: 'Option B'},
                    {id: '3',name: 'Option C'}]
            };

            $scope.data.model = $scope.data.availableOptions[0];

    }]);
})(window.angular);
<body ng-app="ngrepeatSelect">
    <div ng-controller="ExampleController">
        <form name="myForm">
            <label for="repeatSelect"> Repeat select: </label>
            <select name="repeatSelect" id="repeatSelect" ng-model="data.model" ng-options="option.name for option in data.availableOptions track by option.id">
            </select>
        </form>
        <hr>
        <tt>model = {{data.model}}</tt>
        <br/>
    </div>
</body>

Answer №4

<select name="repeatSelect" id="repeatSelect" ng-model="data.model" ng-options="option.name for option in  data.availableOptions track by option.id" ></select>

To learn more, visit: https://docs.angularjs.org/api/ng/directive/ngOptions

If you wish to choose an option:

$scope.data.model= $scope.data.availableOptions[1]; // 1 ==> desired option index

Alternatively, you can select based on a specific property of the object

  angular.forEach($scope.data.availableOptions, function (option, index) {
                        if (option.id === 1) { // 1 ==> desired option's id
                            $scope.data.model= option;
                        }
                    });

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

Incorporating a hyperlink into a ReactJS object's value

I have a ReactJs app with an object containing English translations. Is it possible to make the word "here" in the paragraph a clickable link by adding the URL of description.href? I tried adding it as HTML, but it rendered as text. const EnMessages = { ...

AngularJS directive encounters an error when trying to read the property 'childNodes' of undefined, resulting in a TypeError

I have created a custom directive called "Tab Slide Out" in AngularJS. Here is the code snippet: angular.module('myApp',[]).directive('tabSlideOut', ["$window", "$document", "$timeout", function($window, $document, $timeout) { // de ...

Working with a Mix of Properties in Styled Components

Incorporating a button component with material design using styled-components is my current task. This component will possess various props including size, icon, floating, etc. However, managing the numerous combinations of props has become quite overwhel ...

Select a date from the JQuery calendar, verify it against the database, and display any events scheduled for that date

I am working with a jQuery calendar that stores the selected date in a variable named "X". My goal is to retrieve events stored on that specific date from the Database and display them. Can anyone provide some guidance? <div id="calendar"></div&g ...

What is the best approach for manipulating live data in localStorage using ReactJS?

I am working on creating a page that dynamically renders data from localStorage in real-time. My goal is to have the UI update instantly when I delete data from localStorage. Currently, my code does not reflect changes in real-time; I have to manually rel ...

Using form submission to implement reCAPTCHA v3 in g-recaptcha

Is the Recaptcha API causing trouble? I have the key on both the submit button and the form tag, but it's only sending the sitekey without generating tokens. Any suggestions are welcome. You can either use the key in the form tag: <form method=&qu ...

Issue with ui.router not functioning correctly with dual views

I am having trouble with ui.router as my views are not displaying properly. When I navigate to /manageservices, the content in the left and right html files does not show up on the page. My goal is to have a left and right view displayed on the page. < ...

Displaying an image gradually as the user moves down the page

Recently, I came across this fascinating website: As you scroll down, the images on the site gradually unveil more details, which caught my attention. This unique effect is not something commonly seen on websites, and I'm curious to learn how it is ...

Navigate to a fresh web page without encountering any script loading issues

I am currently working on a web application that loads new pages without requiring the browser to reload. While some pages load perfectly fine, others are causing errors due to missing scripts. The code snippet below is used to load a new page: function lo ...

Encountering issues when attempting to insert information into PostgreSql utilizing AngularJs paired with a C# WebService backend

As a beginner in angularjs, I have set up the HTML file and linked it to the RegistrationController.js. Additionally, I have created the Registration.cs file for managing data retrieval and storage from a database. Despite not encountering any errors, I am ...

Javascript - Transforming tabular information into a hierarchical tree structure (JSON)

When extracting JSON data from a table, the format typically resembles the following simplified structure: https://i.sstatic.net/eqfXM.png The JSON format obtained might look like this: const myObjOriginal = { "rows": [{ "name": "row 1", "cell ...

Ways to boost memory capacity in nodejs

I've been attempting to increase the memory limit in node.js, and to do so I added an environment variable. You can see how I did it here Unfortunately, it doesn't seem to be working as expected. I even tried using capital letters with no succe ...

How I am able to access this.state in React without the need for binding or arrow functions

Understanding the concept of arrow functions inheriting the parent context is crucial in React development. Consider this React component example: import React, { Component } from 'react'; import { View, Text } from 'react-native'; i ...

The selection element is unresponsive to clicks when the ng-click attribute is present in the parent element

Just a quick question. I've observed that when I use an ng-click function above a select element, clicking on the dropdown list doesn't update the value. Here's the HTML code: <div ng-controller="MyController" ng-app> <div ng-cl ...

Using jQuery to append an <option> element to a <select> tag

Every time I try to add an option to a select, the option I want to add gets appended to the first option instead of the actual select element. $(".ct [value='']").each(function() { $(this).append($("<option></option>").attr("val ...

Discover the method of connecting to a unique JavaScript trigger while utilizing IJavaScriptExecutor

In our web application, we have an event called timelineEventClicked that is created by a custom trigger. canvas.addEventListener('click', function (evt) { evt.stopImmediatePropagation(); var mousePos = ge ...

Retaining the Chosen Tab upon Page Reload in Bootstrap 5.1

Struggling to maintain the selected tab active after page refresh. It's worth noting that I'm using Bootstrap 5.1 and have tried various solutions found for different versions without success. <ul class="nav nav-pills mb-3" id=&q ...

Position the text alongside the thumbnail rather than in the center

In the current setup, my username text is positioned in the center of the view. I want to reconfigure it so that it displays directly to the right of the thumbnail. However, removing the alignItems: 'center', property from the item disrupts the e ...

Configuring headless unit testing with requirejs

Seeking a JavaScript unit testing environment, I feel like I'm on a quest for the Holy Grail. The criteria are as follows: testing Requirejs AMD modules isolating each module by mocking out dependencies ability to test in-browser during development ...

Error in NVD3 causing charts to be inaccurately rendered

While utilizing a stacked area chart in the Stacked display mode, there appears to be an issue with the shading under the graph, particularly on the left side of the displayed plot below. We are currently working with d3 v3.4.9 and nvd3 v1.1.15b. Do you ...