How can I make a drop-down field in AngularJS show the current value after populating options in a select control using ng-options?

This conversation centers around an app that can be visualized as,

https://i.stack.imgur.com/Y1Nvv.png

When a user clicks on one of the stories on the left side, the corresponding content is displayed on the right-hand side.

Each story includes a title and a status,

service:

myModule.service('AngelloModel', function(){

    var service = this;
    var stories = [
                {
                    title: 'First story',
                    status: 'To Do',

                },
                {
                    title: 'Second story',
                    status: 'Back Log',                     
                },
                {
                    title: 'Another story',
                    status: 'Code Review',                      
                }               
        ];
    var statuses = [
                  {name: 'Back Log'},
                  {name: 'To Do'},
                  {name: 'In Progress'},
                  {name: 'Code Review'},
                  {name: 'QA Review'},
                  {name: 'Verified'},
                  {name: 'Done'}
              ];

    service.getStories =  function(){
        return stories;
    }

    service.getStatuses = function(){
        return statuses;
    }       
})

factory( a helper/utility function):

myModule.factory('AngelloHelper', function() {

    var buildIndex = function(array, property) {
        var tempArray = [];

        for (var i = 0; i < array.length; i++) {
            tempArray[array[i][property]] = array[i];
        }

        return tempArray;
    }
    return {
        buildIndex : buildIndex
    }
})

controller and module:

var myModule = angular.module('Angello',[]);

myModule.controller('MainCtrl',function(AngelloModel, AngelloHelper){

    var main = this;

    main.stories = AngelloModel.getStories();
    main.statuses = AngelloModel.getStatuses();

    main.statusesIndex = AngelloHelper.buildIndex(main.statuses, 'name');

    main.setCurrentStory = function(story){

        main.currentStory = story;

        main.currentStatus = main.statusesIndex[story.status];

    }
})

html:

<body>
        <div ng-controller="MainCtrl as main">
            <div class="col-md-4">
                <h2>Stories</h2>
                <div class="callout" ng-repeat="story in main.stories" 
                            ng-click="main.setCurrentStory(story)">
                    <h4>{{story.title}}</h4>
                    <p>{{story.description}}</p>
                </div>
            </div>
            <div class="col-md-6 content">
                <h2>Story</h2>
                <form class="form-horizontal">                  
                    <div class="form-group">                        
                        <label class="control-label" for="inputTitle">Title</label>                         
                        <div class="controls">
                            <input type="text" class="form-control"
     id="inputTitle" placeholder="Title" ng-model="main.currentStory.title" />
                        </div>                          
                    </div>                      
                    <div class="form-group">    
                    <div class="controls">
                        <select id="inputStatus" class="form-control"
                            ng-model="main.currentStatus.name"
                            ng-options="l.name for l in main.statuses"></select>
                    </div>    
                </div>                      
                </form>                                         
                </div>
            </div>
        </div>
    </body>

The key point of discussion :

<select id="inputStatus" class="form-control"
                                ng-model="main.currentStatus.name"
                                ng-options="l.name for l in main.statuses"></select>

In the image above, the dropdown values are generated by using

ng-options="l.name for l in main.statuses"

However, the current value does not update when selecting a story, despite including,

ng-model="main.currentStatus.name"

Any recommendations?

Answer №1

When looking at the ng-model you are attempting to assign name as the unique identifier for options. Therefore, it might be beneficial to use select as. For example:

  ng-options="l.name as l.name for l in main.statuses"

This will ensure that the ng-model (

ng-model="main.currentStatus.name"
) is correctly populated with the name and your dropdown will have a preselected value based on the ng-model property.

If you are dealing with an object containing an array of objects with just one property, consider setting a unique identifier (if name is not already one) or simply using an array of names.

In addition, by following this method, you can eliminate the mapping logic (

main.statusesIndex = AngelloHelper.buildIndex(main.statuses, 'name');
) and instead do:

 main.currentStatus = {name: story.status};

Alternatively, set your ng-model as

 <select id="inputStatus" class="form-control"
                        ng-model="main.currentStatus"
                        ng-options="l.name as l.name for l in main.statuses">  
 </select>

and then

 main.currentStatus = story.status;

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

Ways to convert JavaScript object to hashmap

I am attempting to generate a map of type <String, Array()> from a JSON object. Suppose I have the following JSON structure: [ { "userId": "123123", "password": "fafafa", "age": "21" }, { "userId": "321321 ...

Tips for incorporating the multiply times async function into mocha tests

I am attempting to utilize the async function foo multiple times in my mocha tests. Here is how I have structured it: describe('This test', () => { const foo = async () => { const wrapper = mount(Component); const button ...

Managing various iterations of identical repositories

Currently in the process of constructing a library of unique react components that are being utilized in various downstream applications. To incorporate these components into my downstream applications, I rely on the package.json. Recently, I began ponde ...

Different techniques for using percentages in CSS transformations to create dynamic animations for DOM element translations

I have 14 objects positioned across the dom that I need to animate using the translate property. Currently, I am using transform: translate(x%, y%) for each object, requiring me to calculate the translation amount and apply a CSS style individually. This m ...

Tips for disabling viewport resizer while accessing the Console panel in Chrome using Control+Shift+J

Currently, I am utilizing the viewport resizer in Chrome to preview how my code appears on various devices. However, I have encountered an issue - whenever I try to access the console using ctrl + shift + j, the viewport resizer opens instead. You can obs ...

The NodeJS application experiences a crash if incorrect parameters are provided to the API

Currently, I have built a CRUD API using TypeScript with Node.js, Express, and MongoDB. My goal is to ensure that the API functions correctly when the correct parameters are sent through a POST request. However, if incorrect parameters are passed, the Node ...

ESLint detected a promise being returned in a function argument where a void return type was expected

I'm encountering a recurring error whenever I run my ESLint script on multiple routers in my server. The specific error message is as follows: error Promise returned in function argument where a void return was expected @typescript-eslint/no-misuse ...

Utilize the power of Javascript/AJAX or jQuery to submit multiple forms simultaneously

I am currently working on a project which involves having 3 forms on a single page. The reason behind this is that one of the forms is displayed in a modal dialog. My goal is to allow users to submit all 3 forms with a single button click, and I also wan ...

There seems to be some odd behavior with the setIcon function in the Google Maps API

Initially, the marker.setIcon method didn't work for me. Upon inspecting the browser console, I encountered this message: To troubleshoot, I attempted using markerObject.icon = "/Content/img/icon_critical.svg", although it should have been "/Content/ ...

New update in Next.js version 13.4 brings a modification to routing system

I'm currently working with Next.js 13.4 and an app directory. I'm trying to implement a centrally located loader that will show whenever there is a route change anywhere within the app. Since routes/navigation don't have event listeners, I&a ...

Choose a sibling element using CSS styling

As I'm developing an AngularJS component, I am on the quest to identify ANY sibling of a particular tag, irrespective of whether they are div, span, or p. I'm hoping for a CSS-native solution that resembles something along the lines of div:siblin ...

JavaScript: The delayed submission feature is malfunctioning

Visit this link When using JSFiddle, a strange list of errors is generated (see pic here). However, the auto-submit feature on my page works fine, but it lacks the specified delay. Thank you in advance for any assistance. <form id='formBlokUziv&a ...

Create a unique component in ReactJS with the react-google-maps package to enhance your user interface

I would like to integrate a custom marker component into the map, but I have observed that using react-google-maps/api does not support rendering custom components. To illustrate this, here is an example of the code I used: const CustomMarker = ({ text }) ...

Troubleshooting ER_BAD_FIELD_ERROR in a node mysql stored procedure

Encountering an error message while executing the following code: Error: ER_BAD_FIELD_ERROR: Unknown column 'employee_id' in 'field list' Output: { employee_id: '6', employee_name: 'test', employee_contact: ...

CSS: Hover below the designated target to reveal an expanding dropdown menu

My initial solution involved toggling the visibility on and off when hovering. However, this approach is not optimal as the menu should smoothly transition into view. When the visibility is toggled, the user does not experience the intended transition effe ...

Neither setState() nor forceUpdate() trigger the rendering process

I am working with a basic React setup that resembles the following structure: index.js ReactDOM.render(<App />, document.getElementById('root')); App.js export default class App extends Component { constructor(props) { super ...

Uniting the client-side jQuery and server-side Express for enhanced functionality

Currently, I am deepening my understanding of Express/Node. My goal is to construct a basic HTML form that undergoes client-side validation (using jQuery/AJAX) while also being processed server-side (via Express.js). The application's complexity remai ...

Record of Recaptcha actions is not showing up in the reports

My method of running the recaptcha script is as follows: let data = { action: 'homepage' }; grecaptcha.ready(() => { grecaptcha.execute('RECAPTCHASITEKEY', data).then((token) => { recaptcha_token = token; }); ...

The upcoming development does not involve creating an entire HTML webpage using on-demand static site generation (SS

I’m encountering a problem when utilizing getStaticPaths and getStaticProps to create an on-demand SSG for a sharing page. My setup involves Next v12.1.0 and React 17.0.2. After building a specific /[id] page, I can retrieve the data but the HTML output ...

Fetching the second item within an object using JavaScript

I am trying to retrieve the data from the last month of an API, but I want to avoid hard-coding the date like this: const data = [data.data['Monthly Time Series']['2021-11-30']]. I need a way to dynamically access the 2nd object without ...