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

Hiding the initial parent SVG element in the list will also hide all subsequent SVG elements within each section, excluding the container

I encountered a strange issue with my code in the Next framework. When using getServerSideProps, I made a request to my api folder, which resulted in a simple JSON response. Everything seemed to be working fine. The content was displayed perfectly without ...

I am encountering the error 'user.matchPassword is not a function' while making a call to my API using bcryptjs in my Node.js and Express application. Can someone help me understand why

const checkUserAuth = asyncHandler( async (req,res)=>{ const { email , password } = req.body; const foundUser = User.findOne({email}); if(foundUser && (await foundUser.verifyPassword(password))){ generate ...

Ways to customize weekend colors in v-calendar (distinct colors for Saturdays and Sundays)

Looking to customize the appearance of weekends in your calendar by changing their colors? I have a component for the v-calendar that can help with that. Here's the code: <div id='app'> <v-date-picker title-position="left&quo ...

Issue with npm version: 'find_dp0' is not a valid command

Hello, I have a small node application and encountered an issue while running a test. The error message displayed is as follows: 'find_dp0' is not recognized as an internal or external command, operable program or batch file. It seems to be re ...

Having difficulty accessing response data and headers within an AngularJS interceptor

I have a custom API on my server that sends a unique header (let's call it "customHeader") in response to http://localhost:8081/my/test/api. Currently, I am attempting to access this custom response header from an interceptor written in angularJS: an ...

1. "Ensuring the URL of a New Tab Using WDIO"2

During my testing scenario: Navigate to link1 Click a button Open a new tab with link2 How should I verify the link2? I attempted using assert(browser).toHaveUrlContaining(''), but it only verified the link1, causing my test to fail. ...

Error encountered when trying to update Express Mongoose due to duplicate key

In my MongoDB database, I have a unique field called mail. When attempting to update a user, I encounter an issue where if I do not change the mail field, it triggers a duplicate key error. I need a solution where it is not mandatory to always modify the ...

NodeJS/express: server became unresponsive after running for some time

Initially, my service using express and webpack ran smoothly. However, I started encountering an issue where the server would hang with no message code being received, as shown in the server message screenshot (server message screenshot). This problem kept ...

Exploring the Information Within HTML Forms

When my HTML form sends data to the server, it looks like this: { r1: [ '1', '2', '3' ], r2: [ 'Top', 'Greg', 'Andy' ], r3: [ 'validuser', 'invaliduser', 'validuser&a ...

inserting a dynamic variable into a JSON string

My goal is to create a javascript object, var systemName = {"system" : varA}; However, I want the object to be structured like `{"system" :"varA"} where varA contains the variable value but is enclosed in double quotes. I attempted {"system" : "'+ ...

The debut dilemma of Angular.js

I'm currently going through a tutorial and I've hit a roadblock. It seems like I'm missing something crucial, but I can't figure out what it is. //script.js var MainController = function($scope) { $scope.message = "He ...

Is it feasible to have multiple versions of React coexisting in a monorepo?

I have a monorepo set up with npm workspaces: ├─ lib │ └─ Foo └─ src ├─ App └─ Web I am looking to upgrade the Web package to React 18 while keeping App on React 17 My current dependencies are as follows: ├─ lib │ └ ...

Comparing v-show(true/false) and replaceWith: Exploring the best practice between Vue and jQuery

Currently, I am in the process of learning vue.js and have a question regarding the best approach to implement the following scenario: The main query is whether it is acceptable in HTML to write <span></span> followed by a <textarea>< ...

AngularJS - Ensuring the <script> tag is included only after all directives have been rendered

Forgive me if this question has been asked before. I've spent quite some time looking for a solution to no avail. I'm in the process of converting an existing application, which relies heavily on jQuery, to utilize AngularJS. However, I've ...

Effortless 'rotational' script

I am currently developing a HTML5 Canvas game with the help of JavaScript. My aim is to create an object that smoothly transitions to a specific direction. The direction is being stored as a variable and calculated in radians. Here's how the code op ...

Vue.js application failing to display images fetched from the server

When I'm running my Vue.js app locally, the images are loading fine from the "src/assets" folder. However, when I deploy the app to Firebase, the images are not displaying and I get a 404 error. What could be causing this issue? I have tried using: ...

Participating in a scheduled Discord Voice chat session

Currently, I am in the process of developing a bot that is designed to automatically join a voice chat at midnight and play a specific song. I have experimented with the following code snippet: // To make use of the discord.js module const Discord = requ ...

Is there a way to retrieve a value from localStorage and use it to automatically set the selected option in a UL-based dropdown list upon page load

I have implemented a unique UL-based dropdown list that I discovered here (specifically the third model) as the foundation for a role-based selection box for my users. To enhance user experience, I am storing their role selection in localStorage so they do ...

Issue with event binding on datepicker that is dynamically added is not functional

I have integrated the Kendo datepicker into my project, and I am facing an issue with duplicated div elements containing datepickers. The problem is that the datepicker events only fire once on the first duplicated div and then stop working altogether. I ...

Comparing two datetime objects with time zone offsets in JavaScript: How to determine if one is greater than or less than the other?

So I'm faced with a situation where I need to compare two dates where the first date is 05.01.2008 6:00 +5:00 and the second date is 05.01.2008 7:00 +5:00 I'm struggling to find a way to convert these datetimeoffsets into a specific forma ...