Unusual characteristics found in a select list controlled by Angular

The article titled "How to set the initial selected value of a select element using Angular.JS ng-options & track by" by @Meligy served as my guide while working on implementing a select list (ng-options). Despite achieving the desired basic functionality, as shown in this Test Plunk, I still encountered some odd behavior related to the selected item in the list when implemented on my development site.

app.controller("TaskEditCtrl", function($scope) {

  $scope.loadTaskEdit = loadTaskEdit;

  function loadTaskEdit() {
    taskLoadCompleted();
    tasktypesLoadCompleted();
  }

  function taskLoadCompleted() {
    $scope.tasks = [{
        Id: 1,
        Name: "Name",
        Description: "Description",
        TaskTypesId: 4
      }
    ];
    $scope.current_task_tasktypesid = $scope.tasks[0].TaskTypesId;    
  }

  function tasktypesLoadCompleted() {
    var tasktypes = [{ Id: 1, Name: "A" }, 
    { Id: 2, Name: "B" }, 
    { Id: 3, Name: "C" }, 
    { Id: 4, Name: "D" }];

    $scope.available_tasktypes_models = tasktypes    
  }

  $scope.submit = function(){
    alert('Edited TaskViewModel (New Selected TaskTypeId) > Ready for Update: ' + $scope.tasks[0].TaskTypesId);
  }

  loadTaskEdit();    
});

In the HTML:

<form class="form-horizontal" role="form" novalidate angular-validator name="editTaskForm" angular-validator-submit="UpdateTask()">        
        <div ng-repeat="task in tasks">             
          <div>
            <select ng-init="task.TaskTypes = {Id: task.TaskTypesId}" 
            ng-model="task.TaskTypes" 
            ng-change="task.TaskTypesId = task.TaskTypes.Id" 
            ng-options="option_tasttypes.Name for option_tasttypes in available_tasktypes_models track by option_tasttypes.Id">
            </select>
          </div>
        </div>

        <div class="">
          <input type="submit" class="btn btn-primary" value="Update" ng-click="submit()" />
        </div>

      </form>

Although the Test Plunk demonstrates the expected behavior, there are discrepancies between it and my actual implementation. I have included five explanatory images to help pinpoint the issue.

I am struggling with identifying the source of the problem. My intuition suggests a CSS issue may be at play. Has anyone else encountered a similar dilemma? Any insights would be greatly appreciated.

[1 []2 []3 []4

As a novice in CSS, any suggestions or advice are welcome!

CSS https://i.sstatic.net/4oCj9.png

    #region "style sheets"
    bundles.Add(new StyleBundle("~/Content/css").Include(
         "~/Content/css/site.css",
         "~/content/css/bootstrap.css",
         "~/content/css/bootstrap-theme.css",
         "~/Content/css/font-awesome.css",
         "~/Content/css/morris.css",
         "~/Content/css/toastr.css",
         "~/Content/css/jquery.fancybox.css",
         "~/Content/css/loading-bar.css"));
    #endregion "style sheets"

Answer №1

To make the dropdown work correctly, you need to ensure that the model is set to the selected object rather than just the ID of the item. I have made some changes to your code to achieve the desired functionality.

The main differences are:

  1. Assign the ng-model of the dropdown to the selected object instead of the ID of the selected item. This way, you can access all properties of the selected object.

  2. Remove the ng-change binding as it is not needed with two-way data binding. The value on the model (defined by ng-model) will automatically update.

  3. In your HTML, you were referencing properties that were not declared in the Controller $scope. I have updated them to match the available variables in scope.

To learn more about working with dropdowns, refer to the Angular documentation. It provides valuable information for troubleshooting similar issues: https://docs.angularjs.org/api/ng/directive/select

// Your revised code

var app = angular.module("myApp", []);

app.controller("TaskEditCtrl", function($scope) {

  $scope.tasks = {};
  $scope.current_task_tasktypesid = null;
  $scope.selected_task_tasktype = null;

  $scope.loadTaskEdit = loadTaskEdit;

  function loadTaskEdit() {
    taskLoadCompleted();
    tasktypesLoadCompleted();

    
    // Default dropdown selected value
    $scope.selected_task_tasktype = $scope.available_tasktypes_models[2];
  }

  function taskLoadCompleted() {
    $scope.tasks = [{
        Id: 1,
        Name: "Name",
        Description: "Description",
        TaskTypesId: 4
      }
    ];
    $scope.current_task_tasktypesid = $scope.tasks[0].TaskTypesId;

  }

  function tasktypesLoadCompleted() {
    var tasktypes = [{ Id: 1, Name: "A" }, 
    { Id: 2, Name: "B" }, 
    { Id: 3, Name: "C" }, 
    { Id: 4, Name: "D" }];
    
    $scope.available_tasktypes_models = tasktypes

  }
  
  $scope.submit = function(){
    alert('submitted model: ' + $scope.selected_task_tasktype.Id);
  }

  loadTaskEdit();

});
<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.2.9" src="http://code.angularjs.org/1.2.9/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="myApp" ng-controller="TaskEditCtrl as edit">

  <form class="form-horizontal" role="form" novalidate angular-validator name="editTaskForm" angular-validator-submit="UpdateTask()">

    <div ng-repeat="task in available_tasktypes_models">
      
      <div>Task (Id): {{task.Id}}</div>
      <div>Name: {{task.Name}}</div>
      <div>Descripton: {{task.Description}}</div>
     </div>     
      <p>Current Task.TaskTypesId: {{selected_task_tasktype.Id}}</p>

      <div>
        <select
        ng-model="selected_task_tasktype" 
        ng-options="option_tasttypes.Name for option_tasttypes in available_tasktypes_models track by option_tasttypes.Id">
        </select>
      </div>
      <p>{{task.TaskTypes}}</p>
      <p>{{selected_task_tasktypesid = task.TaskTypes}}</p>
      
    

    <div class="">
      <input type="submit" class="btn btn-primary" value="Update" ng-click="submit()" />
    </div>

  </form>

</body>

</html>

Answer №2

Initially, I must acknowledge the implementation by @Meligy and the proposed input of 'dball' as valid. Therefore, proceed in accordance with your preference.

Pay attention to your style sheets.

In conclusion, I have determined that the 'color' style property with a value of 'white' in selector #editTaskWrapper, acting as the identifier of the parent element

<div id="editTaskWrapper"> 

is causing issues. Interestingly, commenting out 'color: white' in

#editTaskWrapper {
    background-color: #337AB7;
    /*color: white;*/
    padding: 20px;
}

results in the selected item in the selectlist becoming visible. This change only affects the visibility of the selected list item, leaving all other controls and values unaffected.

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 do you use CSS and Bootstrap to create a background image that covers one-third of the screen's size?

I have attempted to implement the following using inline CSS along with Bootstrap, but unfortunately it is not functioning correctly. <div class="container" class="img-responsive" class="img-fluid" style="background-image: url('img/projects_cover. ...

The Router.use() function is looking for a middleware function, but instead received an undefined value at the

Currently, I am working on implementing authentication with node.js following a tutorial. However, I have encountered some issues that I am struggling to resolve. This is how I have configured the server: // Inserted code for configuring the server The ...

The input texts are intertwined with one another through an autocomplete function

My latest project involves two input fields, one for ID and the other for Name. When I enter an ID in the first input field and then move to the second (either by pressing tab or clicking), the second input field automatically populates with the correspond ...

Navigating to a specific location and determining its boundaries using the selected location feature in react-leaflet

Is there a way to dynamically zoom in on a particular location or fly to that location when it is selected from a list of cities in a dropdown menu, and then get the bounds around that location? I have been trying to implement this functionality based on t ...

Uploading a Node.js Package to GitHub Packages - Issue ENEEDAUTH

Hello everyone, I am currently attempting to deploy my NPM package to GitHub packages using the following yaml configuration: # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created # For m ...

How to align a child element in the center when the parent is not centered or taking up the full width

I am currently working on building a layout with Bootstrap 4.6, and I am facing an issue with centering the header, columns/cards, and buttons on the page width while the parent container is left-aligned and not full width. Additionally, I need help with ...

Utilize a WebGLRenderTarget in a recursive manner with the power of threejs and GLSL programming

As a newcomer to both ThreeJS and GLSL, I am exploring ways to reuse the output of a fragment shader in another shader, while also utilizing that same output in the subsequent frame of the same shader. Essentially, the output of the shader is dependent on ...

A guide on incorporating the CSS 'content' property with the 'option' tag

Is it possible to include CSS 'content' in the 'option' tag? For example, I want to display "Name: Volvo". <html> <head> <style> option:before { content: "Name: "; } </style> </head> <body> ...

Use jQuery to retrieve the number of items that have been selected in an ASP ListBox

Struggling to find a way to calculate the count of selected items from an ASP listbox using jQuery. Currently, encountering an issue where I am receiving "Cannot get property length of undefined or null reference" on the selectedOptions property. The var l ...

Using jQuery, adjust the width of child elements within a container by applying dynamic CSS styling

I am attempting to dynamically set the width of several child elements using jQuery. Here is what I am trying to achieve: Obtain the count of the desired containers (since there will be multiple instances of the .steps-container class in the DOM) Iterate ...

Show validation message using Bootstrap near the submit button

My form consists of around 40 questions, some required and some optional. Upon clicking "submit," I utilize Bootstrap's form-validation.js to verify the form before submission, which works seamlessly. However, due to the length of the form, when a us ...

How can I utilize match props in React JS with the Context API?

Currently working on a basic application that utilizes context API, fetch, and react hooks for all components except the context API component due to ongoing learning of hooks. The challenge lies in incorporating the match prop within the context API prov ...

What is the purpose of Access-Control-Allow-Headers in an HTTP response and why is it important to include it?

I've been working through a tutorial on using express and have come across the following routes: module.exports = function(app) { app.use(function(req, res, next) { res.header( "Access-Control-Allow-Headers", "x-ac ...

Retrieve MongoDB collection using Node.js

I am completely new to the express/mongo stack, and I have encountered an issue that I was unable to find a solution for on Stack Overflow. Here is my problem: Within my index.js file, the code looks something like this: var mongoose = require('mong ...

Struggling to calculate the total of a property within an array of objects

I'm currently trying to calculate the sum of a specific property within an array object. Although I successfully accomplished this in one component, I am encountering difficulties replicating it in another. The error message being displayed is: this. ...

Exploring Angular 2: Integrating External Libraries

As a beginner in Angular and Angular 2, I am interested in incorporating an external library into my project. The library can be found at the following link: In order to use this library, I added the following line to my index.html file before angular: & ...

Node.js is encountering an error with the post method where req.body is returning an empty

When utilizing cURL or Postman, the operations perform as anticipated curl -d 'username=Johny Sample&title=My First Post&description=We need some assistance cleaning up after the hurricane&postID=Johny Sample_1' http://localhost: ...

having difficulty grasping the variable's scope within this code

Here we have a code snippet where the variable vid is initialized inside a function. The question arises on how this variable can be used outside the function, specifically in the context of vid.play(). How does the program know that vid was created usin ...

When utilizing a wrapped v-text-field, it triggers warning messages and fails to update the data properly

Recently delving into the world of vue.js, I've been experimenting with creating a form using Vue, vuetify, and vuelidate. Oddly enough, when I don't wrap the v-text-field there are no issues, but as soon as I try to encapsulate it within compone ...

Find the IDs of all input boxes that have a specific class attached

Is there a way to retrieve the ID of an input field that has a specific class attribute? For example: <input id="first" class="failed" /> <input id="last" class="failed" /> <input id="city" class="failed" /> <input id="state" class=" ...