Using AngularJS, you can easily preselect an option in a select menu that is populated using ng-options

Exploring how to use AngularJS ng-option directive to populate a select menu and set a default option.

The JSON data retrieved by AngularJS:

{"AF":"Afghanistan","AX":"\u00c5land Islands","AL":"Albania","DZ":"Algeria","AS":"American Samoa","AD"}

The code for populating the select menu:

 angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
     $scope.selectedCountries = null;
     $scope.countries = [];

     $http({
              method: 'GET',
              url: '/api/getCountries'
     }).success(function (result) {
              $scope.countries = result;
     });
 });

The HTML structure of the select menu:

<select name="property_country" ng-model="drpdpwnvalue" ng-options="key as value for (key , value) in countries track by key">
     <option value="">Please choose</option>
</select>

If we want to set "AL" as the default selected option, how can we accomplish this?

Answer №1

To change the value of $scope.drpdpwnvalue to 'AL' in the controller:

angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
     $scope.selectedCountries = null;
     $scope.countries = [];
     $scope.drpdpwnvalue = 'AL'; // added this line
     $http({
              method: 'GET',
              url: '/api/getCountries'
     }).success(function (result) {
              $scope.countries = result;
     });
 });

ng-options works together with ng-model, so changing the value of ng-model will be handled by Angular automatically

UPDATE: After debugging, it was discovered that using track by key is causing issues. This should be removed. A working example can be found on this plunker link.

Answer №2

Consider using the ng-selected directive on the option element.

<select ng-model="drpdpwnvalue" ng-model="selectedCountries">
     <option value="{{key}}" ng-repeat="key as value for (key , value) in countries track by key" ng-selected="key === 'AL'">{{value}}</option>
</select>

Answer №3

After trying various Angular solutions without success, I was able to accomplish the task by utilizing JQuery:

    $( document ).ready(function() {
        $.getJSON("/api/getCountries", function(result) {
            var options = $("select[name=property_country]");

            $.each(result, function(key, value) {
                options.append($("<option />").val(key).text(value));
            });

            $('select[name=property_country] option[value="AL"]').attr("selected", "selected");
        });
    });

It's worth noting that this solution is for reference purposes only and may not be the preferred method as it relies on JQuery.

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

Employing an angular ng-model expression

Inside a controller: $scope.bar = {'label': 'user_label', 'bindTo': 'user.name'}; Next, in the HTML: <label for="user_label">User Label</label> <input name="{{bar.label}}" type="text" class="form-co ...

Utilizing JavaScript as an alternative to PHP in this specific scenario

Hey everyone, I'm looking to pass data from PHP to JavaScript. Below is my PHP code that I need to adapt for use in JavaScript: $result = dbMySql::Exec('SELECT Latitude,Longitude FROM data'); while ($row = mysqli_fetch_assoc($result)) $ ...

What is the best way to overlay text onto a background image using Material UI's Card and CardMedia components?

Using the card component, I have successfully added a background image. However, I am facing difficulty in figuring out how to overlay text on top of this image. If anyone has suggestions or alternative methods, please feel free to share! <Card> ...

Tips for Saving JSON Response from Fetch API into a JavaScript Object

I am facing an issue trying to store a Fetch API JSON as a JavaScript object in order to use it elsewhere. The console.log test is successful, however I am unable to access the data. The Following Works: It displays console entries with three to-do items: ...

Strategies for streamlining repetitive code within a closure in Angularjs

We are currently utilizing Angularjs 1x and I am in the process of refactoring some repetitive code within an Angularjs filter. However, I am facing challenges in getting it to function correctly. It should be a straightforward task. Our standard approach ...

What is the process of uploading a file from a Vue.js app to the local public disk in Laravel?

Hello there, I am looking to upload a file from a Vue.js app to the local public directory of Laravel and only store the unique name in MySQL upon form submission. However, I am unsure how to achieve this using JavaScript. // Template Tag <input type= ...

Operating with JavaScript arrays and objects

My JavaScript array/object consists of the following data: [ { "name": "A", "selected_color": "Red" }, { "name": "B", "selected_color": "Green" }, { ...

Creating a paragraph from text inputs using React

I'm currently working on code that retrieves input from two textboxes - one for a string value and one for a number value. I want this data to be displayed in real-time within a paragraph without the need for a submit button. I've been struggling ...

An 'Syntax Error' message appears in Internet Explorer when JSONP does not receive a response

Our current application needs to retrieve information from another application, and this second application does not have to be active to respond to the JSONP request. In this case, the requester will receive an alert message informing them of this. funct ...

When using Jquery, the search button consistently retrieves the same data upon the initial click event

How can I ensure that my Ajax call retrieves data from the remote database based on the updated search criteria every time I click the search button? Currently, the system retrieves results based on the initial search criteria even after I modify it and cl ...

Removing a single duplicated element from an array using jQuery

I'm facing an issue where if I try to remove the first element that I added using the button, all elements in the array get erased. However, when I remove the last element pushed, it works just fine. To tackle this problem, I attempted to use $.inArr ...

What is the reason for the visibility of my API key when utilizing next.js alongside environment variables?

I recently went through the next.js documentation and implemented a custom API key on my now server. However, I encountered an issue where when I execute now dev and navigate to the sources tab, my API key is visible. https://i.stack.imgur.com/kZvo9.jpg ...

The onload event for embedding SVG files is not functioning as expected

I created an angular directive: <div> <embed ng-src="{{url}}" id="map" type="image/svg+xml/> </div> I am trying to trigger a function when the svg is fully loaded. To achieve this, I have added an onload action listener durin ...

Exploring JavaScript Regular Expressions in Internet Explorer 11

I am attempting to eliminate all non-digit characters from a string using JavaScript. While this code works properly in FF and Chrome, it does not work in IE11 and no characters are removed. var prunedText = pastedText.replace(/[^\d\.]/g,""); ...

Istanbul provides me with a thorough analysis, yet it always seems to conclude with an error

Currently, I am experimenting with a basic application (found in the Mocha tutorial code available at ) to troubleshoot why Istanbul is giving me trouble. The issue is that Istanbul successfully generates a coverage summary but then throws an error for unk ...

The request body is not showing up as a key-value pair, while the request headers and other parameters are visible

Example of 'Advanced REST Client' Request I am currently using Postman and Advanced REST client to create a simple POST request based on the code below: 'use strict'; var express = require('express'); var bodyParser = requir ...

What is the best way to incorporate a new attribute into an array of JSON objects in React by leveraging function components and referencing another array?

Still learning the ropes of JavaScript and React. Currently facing a bit of a roadblock with the basic react/JavaScript syntax. Here's what I'm trying to accomplish: import axios from 'axios'; import React, { useState, useEffect, useMe ...

Exploring the power of React Hooks with the useState() function and an array filled

When creating new "Todo" items and modifying the fields, everything works fine. However, my problem arises when trying to retrieve the child data after clicking the "show all objects" button. To better understand my issue, here is a code example: const Co ...

Bringing in States and Functions to a React Component

Is there a way to improve the organization of states and functions within a functional React Component? Here's my current code structure: import React from 'react' //more imports... const Dashboard = () => { const [] = useState() / ...

The android webview is having trouble loading HTML that includes javascript

I have been attempting to showcase a webpage containing HTML and JavaScript in an android webview using the code below. Unfortunately, it doesn't seem to be functioning properly. Can someone provide assistance? Here is the code snippet: public class ...