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

Tips for converting ActiveRecord hierarchy into a JavaScript array

Currently, I am in the process of incorporating a treeview feature into my institution model within my rails application. To accomplish this, I have integrated the ancestry gem into my model successfully and included the treeview component into my view wit ...

Is there a way for me to showcase the most recently added item above the existing one?

Is there a way to show the most recently added item at the top of the list instead of at the bottom? <div className="App"> <h2>{this.state.title}</h2> <form ref="myForm" className="myForm"> <input type="tex ...

Having trouble retrieving an object through a GET request in Node.js with Express

Currently, I am going through a tutorial on Node.js by Traversy Media and I have encountered an issue that has me stumped. The problem arises when I attempt to retrieve the response of a single object from an array of objects using the following code: app ...

JavaScript code to obscure

My goal is to create a JavaScript function where the "costCenter" object starts with visibility set to false. However, when the user clicks on the "computer" item in a dropdown list, the visibility of "costCenter" should change to true. This is my current ...

Error message in Node.js with Multer: The function '.array' is not recognized

I've spent the last two days searching for a solution to this issue, but the only reference I could find was an unresolved problem reported on version 1.1.0: https://github.com/expressjs/multer/issues/338 I am using the Node.js SDK and Express framew ...

Exploring the world of SPA: Implementing Data Transfer Objects

Considering implementing a Single Page Application (SPA) using a JavaScript framework like Angular JS. Currently, I have multiple existing Web APIs containing the necessary information for the app. I need to add another API that will handle new data and re ...

Deleting lines from JSON object using Angular or JavaScript

On my webpage, I have a list where you can add a new line by pressing the "+" button (easy with push), but I'm not sure how to remove lines using the "X" button. https://i.stack.imgur.com/nm06A.png This is the JSON structure: "priceExtra" : [ ...

Combine an array of objects into a regular object

Imagine having an array structure as shown below: const student = [ { firstName: 'Partho', Lastname: 'Das' }, { firstName: 'Bapon', Lastname: 'Sarkar' } ]; const profile = [ { education: 'SWE', profe ...

What are the advantages of implementing filters in AngularJS?

I'm confused about the benefits of using filters in Angular compared to regular functions. From a functional standpoint, they seem almost identical. Is there something happening in the background that I'm missing, or is it more about improving th ...

Is it possible to create a pie chart using Chart.js with data fetched through an Ajax HTTP GET

Embarking on a new journey here, this week's focus is on delving into Chartjs for canvas and brushing up on JSON usage. The task at hand includes employing an Ajax HTTP GET request to fetch the json file. However, I am currently stumped on how to trig ...

What is the best way to design a webpage that adapts to different screen heights instead of widths?

I'm in the process of designing a basic webpage for a game that will be embedded using an iframe. The game and text should always adjust to fit the height of your screen, so when the window is small, only the game is displayed. The game will be e ...

Storing a single array from a nested array into the state of a React component

As a new enthusiast in the world of React, I could really use some guidance. Currently, I have an array stored in a state variable called projects 0:{id: 1, title: "Business Web", category: "Web Design", deleted_at: "0000-00-00 00:00:00"} 1:{id: 2, title ...

swap out the CSS class for my own class dynamically

When I display HTML code like this <div class="btn btn-pagination"> <i class="fa fa-angle-right"></i> </div> and want to replace fa fa-angle-right with myClass when the page loads. I attempted: $(document).ready(function () { ...

Issues with reloading when passing POST variables through Ajax requests

I have a button with the id #filter <input type="button" name="filter" id="filter" value="Filter" class="btn btn-info" /> Below is the Ajax script I am using: <script> $(document).ready(function(){ $('#filter').click(function() ...

Problem encountered when utilizing dat.GUI in a three.js demonstration

I recently experimented with using dat.GUI in a specific three.js example. To integrate a GUI for adjusting mesh opacity, I made the following code modifications. var loader=new THREE.VTKLoader(); loader.load ("models/vtk/bunny.vtk", function(geom){ var ...

Traverse JSON object as a string

I'm new to working with JavaScript. I have a JSON string that was created using the Google Gson API, and I'm passing this string to a JavaScript function. The JSON string looks like this: '{"validationCode":"V10291","caseNumber":"2010CF1010 ...

Obtain and display pictures in HTML

I am working on a code snippet that fetches images from a directory and displays them in HTML. The issue I'm facing is that the images in the directory keep changing every second, causing problems on mobile browsers where the cached images are not bei ...

Tips for ensuring the Google+ JavaScript tag is W3C compliant

I have a Google+ button on my website that is functioning properly. However, when I run it through the W3C validator, an error is detected: The text content of the script element does not meet the required format: It was expecting a space, tab, newlin ...

Is it possible to have the ShowHide plugin fade in instead of toggling?

I'm currently utilizing the ShowHide Plugin and attempting to make it fade in instead of toggle/slide into view. Here's my code snippet: showHide.js (function ($) { $.fn.showHide = function (options) { //default variables for the p ...

Error message: The 'Access-Control-Allow-Origin' policy is preventing access in a react express docker application

I have successfully set up a front-end React application and a Node/Express API using Docker. The React app is currently running on localhost:3000, while the API is running on localhost:9000. Both applications are fully functional. However, I am encounteri ...