What is the best way to establish a default selection in Angular?

After retrieving JSON data from the server, it looks something like this:

$scope.StateList = {"States": [
    {
        "Id": 1,
        "Code": "AL",
        "Name": "Alabama"
    },
    {
        "Id": 2,
        "Code": "AK",
        "Name": "Alaska"
    },
    {
        "Id": 3,
        "Code": "AZ",
        "Name": "Arizona"
    },
    {
        "Id": 4,
        "Code": "AR",
        "Name": "Arkansas"
    }]}

$scope.Address = {"Address": {
    "Address1": "123 Maple" ,
    "Address2": null,
    "City": "Tempe",
    "State": "AZ",
    "ZipCode": null,
    "Country": null,
    "Id": 0,
    "Latitude": 0,
    "Longitude": 0
}}

A select setup has been implemented as shown below:

<select ng-model="Address.State">
    <option ng-repeat="template in StateList.States">{{template.Code}}</option>
</select>

The goal is to bind the Address.State field to the selected value, setting it as the initial option for the select input. So far, I have been struggling with achieving this and would appreciate any guidance on what might be missing. Here is a plunker where you can interact with a live version.

Answer №1

If you want to dynamically create options in a select dropdown using AngularJS, you can make use of the ng-options directive along with ngModel. Here's an example:

<select ng-model="Address.Address.State" 
         ng-options="state.Code as state.Name for state in StateList.States"></select>

Plnkr Demo

This code snippet follows the syntax:

"select" as "label" for "value" in "array"

Answer №2

If you prefer, you have the option to utilize ng-options as recommended by PSL or you may opt for using the value attribute within the options.

<option ng-repeat="template in StateList.States" 
       value="{{template.Code}}">{{template.Code}}</option>

PLUNKER LINK

Answer №3

For select dropdowns, it is recommended to utilize the ng-options binding instead of ng-repeat for iteration purposes. The following code snippet showcases how to display default text and dropdown options:

<select ng-model='Address.State' ng-options="template.Code for template in StateList.States" >
    <option value=""> Please select one </option>
</select>

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

How can I display a popup window within an iframe on a separate full page?

I am facing an issue while creating an HTML table using AngularJS with a popup. The problem is that I want the popup window, which shows a graph, to open up on the entire page instead of in a specific div. My desired output should look like this: https://i ...

Add a new key-value pair to the mock data by clicking on it

Hey there! I'm currently tackling a task that involves toggling the value of a boolean and then appending a new key-value pair on click. I've been attempting to use the . operator to add the new key-value pair, but it keeps throwing an error. In ...

Failure to populate AngularJS view

I am a beginner in AngularJS and I am attempting to create a page similar to the example provided here. While the example works perfectly when copied from the link above, I am facing difficulties trying to integrate it into my folder structure as displaye ...

Use Onblur and Onfocus events in an input field that is read-only

Here is an input field: <input class="" type="text" id="Name_11_1" name="Name" value="Your name:"> I would like to modify it as follows: <input class="" type="text" id="Na ...

The discord.js argument for startsWith should not be a standard regular expression

https://i.sstatic.net/UG79z.png What could be the reason behind this not working as expected? I am trying to check if a string starts with a number, and furthermore, I want it to handle multiple numbers. For instance, if the string starts with 1259823 the ...

Troubleshooting Material-UI: The Mystery of the Missing Dialog

I have been struggling with getting a pop-up dialog to appear when a form is incorrectly filled out. Despite my efforts, the code that should trigger the dialog upon submission does not seem to be working as expected. The function renderError(), responsib ...

What is the best way to access and utilize the data stored in my database using mySQL, PHP, and JavaScript?

My Objective : When a user selects a location from the dropdown list, I want the function "newMark()" to place a marker on Google Maps; Current Achievements : The map is displayed along with the select field containing all locations saved in my database. ...

The AngularJS HTTP interceptor is a crucial component for handling

Is there a way to use an interceptor in AngularJS to log "finished AJAX request" when any request is completed? I've been exploring interceptors and currently have the following setup, but it triggers at the beginning of the request rather than the e ...

Error encountered while attempting to save process using ajax - 500 Internal Server Error

I am facing an issue with my CodeIgniter code where I encounter a 500 internal server error when trying to save data. I am not sure why this problem is happening and would appreciate any help. Below is the AJAX code in the view: function save() { $(& ...

The dynamic Vue.js transitions and effects are like a magic

I am using a v-for to render multiple child components: <div v-for="(pass) in scoringPass" :key="pass.decision"> <Pass :pass="pass"/> </div> Each of these child components contains a transition tag: &l ...

Conflict between Angular's ng-repeat directive and Sass styling

Currently, I am working on a project and encountering an issue that is causing some difficulty: In order to create a navigation bar with equally distributed list elements based on the number of items, I am utilizing ng-repeat for data binding and Sass for ...

How can I ensure that I only include a field in a JavaScript object if the value is not null?

In my current setup, I am utilizing mongoose to write data to a MongoDB collection while ensuring there are no null fields. Default values have been set in the document for this purpose. During an update function call, certain fields may be null but I do n ...

Creating a unique texture on a spherical object using THREE.js

Can a sphere be textured in sections rather than all at once? Just like we can use 6 textures on 6 sides of a cube, is it possible to apply different textures to different parts of a sphere? For example, dividing the sphere into quarters and texturing each ...

Update information across controllers using a shared service

Whenever I implement this code, it functions correctly: angular.module('app').service('DataService', function() { return {theme: "amelia"} }); However, when I try this code snippet, there is no update. Can you please explain the di ...

Open a submenu when clicking on an input field and automatically close it when the focus is lost

Is there an easier way to create a submenu that opens on input click and closes when losing focus using jQuery? Right now, I have achieved this functionality with the following code: $(document).mouseup(function (e){ var container = $(".container"); ...

Utilize Hardhat and NPM to distinguish between unit tests and integration tests efficiently

Struggling with setting up two commands in my package.json for running unit tests and integration tests. I am having trouble defining the location of the testset for each type of testing. Within the scripts section of my package.json, I have created two c ...

Tips for ensuring that a THREE.Group is always displayed in front of other objects

I am attempting to display a set of transform controls in such a way that they are constantly visible to the user. However, when I disable DepthWrite or apply the AlwaysDepth function to the transform controls, I achieve the desired result but encounter an ...

Verify if the user possesses legitimate Jira REST API credentials

I am currently using the npm module jira-client to send API requests to my Jira system. I need a way to verify whether the user has valid credentials before proceeding. Depending on the validation result, I plan to either: Inform the user that their use ...

JavaScript encountered an issue when trying to display HTML content

Through my PHP code, I am attempting to create a popup window that displays the content of an HTML file. However, after adding script tags, no HTML content is displayed. When I tried echoing out $row2, only the word 'array' appeared on the screen ...

Exploring the method of creating multiple nested states within various parent components while utilizing identical templates

I have developed a mobile site for purchasing, renewing, and transferring domains. The app consists of 4 templates that work together in a functional chain. Buy : Search -> (login if necessary?) -> Pay -> Confirmation Renew : Choose -& ...