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

The most effective method for incorporating a header and footer into an HTML page utilizing a variety of client-side frameworks

Looking for a solution for my HTML project where I want to incorporate a header and footer to minimize rework. Any suggestions on a good approach? I have experimented with AngularJS using ng-include, and here is the code snippet: var app = angular.module ...

Creating a bold portion of a string

My task involves dynamically creating <p> elements within a div based on the contents of my codeArray, which can vary in size each time. Instead of hard-coding these elements, I have devised the following method: for(i=1;i<codeArray.length;i++) ...

Using JQuery to eliminate the current div in an image slider

I currently have an image slider that allows users to switch between images. There are two buttons - one adds a new item to the slider, while the other is supposed to remove the current image from the slider, but it doesn't seem to be working properly ...

Issue with jQuery's JSON data not being properly transmitted to CodeIgniter (`

Based on my observation, the script provided below seems to be functioning properly: <script type="text/javascript" language="javascript"> $(document).ready(function() { $('#add').bind('keypress', function(e) { if(e.k ...

Node.js - CSRF Protection Token Undefined

I've been facing challenges with setting up CSRF token generation, and I seem to be missing something. server.js: // configuration ====================================================================== var express = require('express'); va ...

Place the Div directly above a distinct Div

Hey there! I'm currently working on positioning one div on top of another div programmatically (using javascript or css). These divs are completely separate and have the following structure: <div class="bottom"> <img src="image"></i ...

Can the contents of a JSON file be uploaded using a file upload feature in Angular 6 and read without the need to communicate with an API?

Looking to upload a JSON file via file upload in Angular (using version 6) and read its contents directly within the app, without sending it to an API first. Have been searching for ways to achieve this without success, as most results are geared towards ...

Display data from two arrays in real-time

The following data is available: "PensionPlanSummary": [ { "Type": "DefinedContributionPension", "Participants": [ { "Year": 2018, "Value": 425.0 } ...

JavaScript: The Battle of Anonymity - Anonymous Functions vs Helper

I'm currently grappling with a piece of functional style code that is featured in the book Eloquent Javascript: Here's the issue I'm facing: When I have the count() function passing an anonymous function to reduce(), everything seems to wor ...

What is causing the premature termination of the for loop?

I am currently utilizing Node.js (with nodemon as the server) to upload an excel file, parse its contents, and then send each row to a MongoDB database. The total number of rows in the array is 476, however, the loop seems to stop at either 31 or 95 withou ...

Encountering an Invariant Violation: React does not allow objects to be used as children

I can't figure out why my code isn't working. Every time I run it, I get the error message: Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of chil ...

I need help using i18N to translate the SELECT option in my VUE3 project. Can someone guide me

<n-select v-model:value="value" :options="options" /> options: [ { label: "Every Person", value: 'file', }, { label: 'Drive My Vehicle', ...

Incorporate JavaScript code into contentWindow

Attempting to utilize a Javascript postMessage function, similar to how it can be done with an iframe, but now with an embed element. The reason for using an embed is due to the bug in IOS devices which causes issues with setting iframe width and height. ...

Adding an image to a React component in your project

I am currently working on an app that utilizes React and Typescript. To retrieve data, I am integrating a free API. My goal is to incorporate a default image for objects that lack images. Here is the project structure: https://i.stack.imgur.com/xfIYD.pn ...

Is the `document.documentElement` consistently defined and always representing the HTML element?

I am looking to make changes to the <html> element using a script within the <head> section of an HTML page. My goal is to only access and modify the <html> element itself, without affecting any of its children. Should I wait for the DOM ...

Can anyone recommend a user-friendly JavaScript dialog box compatible with jQuery that is mobile-responsive?

Mobile browsers. Using Jquery dialog alert box. Avoiding the use of alert() due to its unattractive appearance in web browsers. In the process of creating a website for both mobile and web platforms, seeking a dialog box that is compatible with both. ...

The focus behavior of React refs varies across different browsers such as Chrome, Firefox, and IE

While working with refs in react, I observed that the .focus() method behaves differently in Chrome and Firefox. https://i.stack.imgur.com/rjSsZ.png In this sandbox https://codesandbox.io/s/a-guide-to-react-refs-2nd-example-vl9sj?file=/src/Ref.js I have ...

Is there a way to remove information with react and axios?

While working on a project, I encountered an issue with using .map() to create a list. When I console log the user._id on my backend, it displays all the ids instead of just the one I want to use for deleting individual posts by clicking a button. Each pos ...

Removing items dynamically from a list created using ng-repeat

I have an array of nested JSON objects and I am using ng-repeat to create a list with the nested arrays. My goal is to dynamically delete items from this list upon button click by calling a function in the controller: $scope.remove= function(path){ va ...

The InjectionToken component is not exported by AngularFire

I am running into some challenges while trying to develop an Angular-Fire application. I was following a specific tutorial which can be found at: However, when I integrate angular-fire into my application, I encounter an issue where the "server" fails to ...