Setting default values for dropdowns in ng-repeat using AngularJS

I am working with an array of objects that have three properties:

attorneyId, attorneyName, and attorneyList
. The attorneyList should be displayed as a dropdown menu. If both attorneyId = null and attorneyName = null, then the dropdown will only show Choose attorney. On the other hand, if either attorneyId != null or attorneyName != null (or both), the dropdown should display the values present in attorneyId and attorneyName.

To achieve this, I am creating an object called

selectedAttorney = {id:list.attorneyId, name:list.attorneyName}
and passing it to the ng-model directive of the select element. Although the correct values are being captured in the selectedAttorney when changing the dropdown selection, the issue arises when there are pre-existing values for attorneyId and attorneyName; the dropdown does not pre-populate those values.

Here is the HTML:

<div ng-repeat='list in List'>
  <div class="width-200" ng-init="selectedAttorney = {id:list.attorneyId, name:list.attorneyName}">
    {{selectedAttorney}}
    <select ng-model="selectedAttorney" ng-options="attorney.name for attorney in list.attorneyList">
      <option value="">-- choose attorney --</option>
    </select>
  </div>
</div>

JS

$scope.List = [ {
  "attorneyId": "3",
  "attorneyName": "Robert",
  "attorneyList": [
    { "id": 1, "name": "sue" },
    { "id": 2, "name": "anthony" },
    { "id": 3, "name": "Robert" },
    { "id": 4, "name": "George" },
    { "id": 5, "name": "Bruce" }
  ]
},
{
  "attorneyId": null,
  "attorneyName": null,
  "attorneyList": [
    { "id": 1, "name": "sue" },
    { "id": 2, "name": "anthony" },
    { "id": 3, "name": "Robert" },
    { "id": 4, "name": "George" },
    { "id": 5, "name": "Bruce" }
  ]
}
];

Link to Plunker:

http://plnkr.co/edit/eqBkX0DNleiFmlO5sm7J?p=preview

Thank you for your help.

Answer №1

While your approach is valid, I find it more effective to structure my select boxes in the following manner.

<select ng-model="selectedAttorney">
        <option 
           ng-repeat="attorney in list.attorneyList"
           title="{{attorney.name}}"
           ng-selected="{{attorney.id == selectedAttorney.id}}"
           value="{{attorney}}">{{attorney.name}}
       </option>
</select>

For a live demonstration of this updated method, you can visit: http://plnkr.co/edit/vCNOAPWlR6Mj1kFOgCKT?p=preview

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

Problem encountered when trying to show the Jquery Ajax response on an HTML page

I'm facing a challenge with loading a page that needs to display values with dynamic pagination. To retrieve these values, I am making a REST call which returns a JSON object. Although I can see the JSON output in the browser console, I am unable to d ...

Using Angular and Capacitor Filesystem to search for specifically PDF files during exploration

I have been utilizing the code below to navigate through the file system in an ionic App and save files to the device for future uploading. import { Component, ElementRef, ViewChild } from '@angular/core'; import { Filesystem, Directory } from &a ...

Create an interactive list with the ability to be edited using HTML and

I'm currently working on a UI scenario that involves a text box field with two buttons beneath it. When the user clicks the first button, a popup will appear prompting them to input an IP address. Upon submitting the IP address in the popup, it will b ...

Combining res.json and res.render to send MongoDB data to AngularJS: A guide

Utilizing express with the jade template engine is my current setup in my project. app.js // Setting up the view engine app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); For each temp ...

The Material UI Menu does not close completely when subitems are selected

I am working on implementing a Material UI menu component with custom MenuItems. My goal is to enable the closure of the entire menu when clicking outside of it, even if a submenu is open. Currently, I find that I need to click twice – once to close the ...

Common mistakes made while working with decorators in Visual Studio Code

Having trouble compiling TypeScript to JavaScript when using decorators. A persistent error message I encounter is: app.ts:11:7 - error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the ' ...

Issue encountered when attempting to utilize multiple datasets with Twitter Typeahead/Bloodhound

Hello, I am currently learning how to use Typeahead and Bloodhound with the latest javascript. Below is a snippet of my code: Html: <div id="multiple-datasets"> <input class="typeahead" type="text" placeholder="NBA and NHL teams"> </div ...

Determine if the input text field contains any text and store it in a variable using jQuery

I'm working on a form that includes radiobuttons and textfields. To keep track of the number of checked radiobuttons, I use this code: var $answeredRadiobuttons = $questions.find("input:radio:checked").length; But how do I store the number of textf ...

What could be causing the lack of value appearing after I clicked the button?

Setting the value for the array of images as an empty string does not return the expected result. When I move one of the 4 images and click the button, I anticipate a new array with the information of one of the four images including src, x, and y coordina ...

Gather information from a customizable Bootstrap table and store it in an array

Currently, I have a bootstrap table configured with react-bootstrap-table-next, enabling users to edit cells and input their desired values. After completing the editing process, individuals can click on the "Submit" button to save the table values, which ...

I recently created a "dist" folder through Babel. Is it possible to integrate the files within this folder directly into a fresh React project?

I have a React library that is available on npm. My process for publishing it involves the following steps: To begin, I create a folder called dist using Babel by executing this command- babel ./src -d ./dist Next, I upload the resulting dist directory ...

"Error: The functionality of finding places on Google Maps is not

I've encountered an issue while trying to integrate Google Maps into my Node application. The map is loading correctly and I'm able to retrieve my location. However, I am facing a problem with implementing the Google Places API code to allow user ...

The GLTF 3D model failed to animate as expected

My current objective is to create an animation for a 3D model that I have imported as a .gltf file. The model contains only one animation. After carefully following the steps outlined in the documentation: And exploring various examples on the internet, ...

HTML dynamic voting system

I'm new to coding in HTML and I have a specific challenge that I need help with. I want to display a value on my webpage that increases every time a user clicks a button. Below is the code I have written so far: <script type="text/javascript& ...

I encountered a problem with routing in my MERN project while trying to implement a feature I learned from a YouTube tutorial

My first question on stackoverflow. To summarize: I followed a YouTube video and downloaded the course code from the GitHub link provided, but I'm encountering routing issues despite reading similar questions on stackoverflow. I've been followi ...

Conceal a div and label after a delay of 5 seconds with a JavaScript/jQuery function in C#

Here is a sample div: <div class="alert alert-success alert-dismissable" runat="server" visible="false" id="lblmsgid"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ...

Angular JS form cloning feature

I'm facing a challenge in creating a dynamic form with multiple sections. At the end of the form, I want to include a "Add New Form" button which will duplicate the existing form below it, each with its own save button. What's the most effective ...

Ensure that the elements within the container automatically adjust their height to fill the entirety of the

I am facing a challenge in getting the items within a container to occupy the space in the desired way. The main issue lies in the fact that flexbox and CSS grid are designed to adjust to changes in width rather than height, whereas I require the opposite ...

Encountered an issue during the creation of a Nuxt.js project using the command line tool, where a SyntaxError was triggered

I encountered an issue while attempting to set up a nuxt.js starter project using the nuxt cli. Here are the steps I followed: Installed vue cli globally with the command: npm install -g vue-cli Created the project using: vue init nuxt-community/star ...

How can you selectively add a CSS class during the iteration of a VueJs object?

Using Vuetify components: <v-layout row wrap> <v-flex xs2 v-for="(month, key) in months" :key ="key"> <router-link class = "decoration" :to="month.target">{{(month.month)}}</router-link> </v-flex> The "v ...