Tips for assigning a value in a dropdown menu with AngularJS

Can someone help me with setting the same value in multiple drop-down lists using angular.js? Below is an explanation of my code.

<table class="table table-bordered table-striped table-hover" id="dataTable">
  <tr>
    <td width="100" align="center">Time <i class="fa fa-long-arrow-right"></i>
      <BR>Day <i class="fa fa-long-arrow-down"></i>
    </td>
    <td width="100" align="center" ng-repeat="hour in hours" ng-bind="hour"></td>
  </tr>
  <tbody id="detailsstockid">
    <tr ng-repeat="days in noOfDays">
      <td width="100" align="center" style=" vertical-align:middle" ng-bind="days"></td>
      <td width="100" align="center" style="padding:0px;" ng-repeat="hour in hours">
        <table style="margin:0px; padding:0px; width:100%">
          <tr>
            <td>
              <select id="coy" name="coy" class="form-control" ng-model="sub_name " ng-options="sub.name for sub in listOfSubjectName track by sub.value">  
            </select>
            </td>
          </tr>
          <tr>
            <td>
              <select id="coy" name="coy" class="form-control" ng-model="fac_name " ng-options="fac.name for fac in listOfFacultyName track by fac.value">  
            </select>
            </td>
          </tr>
      </td>
      </table>
      </td>
    </tr>
  </tbody>
</table>

The values are being set dynamically in each row of this table, and the values are the same for all rows and columns. The code for my controller file is provided below.

 $scope.noOfDays = [];

        $scope.days = {
          '0': "Monday",
          '1': 'Tuesday',
          '2': 'Wednesday',
          '3': 'Thursday',
          '4': 'Friday'
        }

        $scope.hours = [
          '9AM :: 10AM',
          '10AM :: 11AM',
          '11:15AM :: 12:15PM',
          '12:15PM :: 01:15PM',
          '02PM :: 03PM',
          '03PM :: 04PM',
          '04PM :: 05PM'
        ]

        for (var i = 0; i < 5; i++) {
          $scope.noOfDays.push($scope.days[i]);
        }
        $scope.listOfSubjectName=[{
        name: 'Select Course',
        value: ''
        }]
        $scope.listOfFacultyName=[{
        name: 'Select Faculty',
        value: ''
        }]

If I select a value from the Select Course dropdown list under '12:15PM :: 01:15PM', that selected value should automatically be set in the next 3 sets of times (

i.e. '02PM :: 03PM','03PM :: 04PM','04PM :: 05PM'
) and displayed in the Select Course dropdown lists corresponding to those times. I can select the value from anywhere, but once selected, it should be set in the next 3 dropdown lists. Can someone assist me with this functionality?

Answer №1

If you want to achieve the desired functionality, you can refer to the solution provided in this [jsFiddle]. To trigger changes in the next select items, ensure that you call a method on the ng-change event like shown below:

<select class="form-control" ng-model="sub_name[days + hour]" ng-change="setSub(days, hour)"  ng-options="sub.name for sub in listOfSubjectName track by sub.value">

The methods outlined should function as follows:

$scope.setFac = function(day, hour){
    console.log("set fac "+ day + ", " + hour);
    var next = 0;
    $scope.hours.forEach(function(hr){
        if(hr === hour || next){
            next++;
        }
        if(next > 0 && next < 4){
            $scope.fac_name[day + hr] = $scope.fac_name[day + hour];
        }
        else{
            // clear previous selection
            $scope.fac_name[day + hr] = null;
        }
    });
};  

$scope.setSub = function(day, hour){
    console.log("set sub "+ day + ", " + hour);
    var next = 0;
    $scope.hours.forEach(function(hr){
        if(hr === hour || next){
            next++;
        }
        if(next > 0 && next < 4){
            $scope.sub_name[day + hr] = $scope.sub_name[day + hour];
        }
        else{
            // clear previous selection
            $scope.sub_name[day + hr] = null;
        }
    });
};

To ensure proper functioning, it is crucial to assign unique identifiers to your models within each select item using the days and hour values. Failure to do so may result in all select elements acquiring the same value when one is selected.

EDIT: revised code according to feedback

Answer №2

When an item is selected in the control, both the control's value and listOfSubjectName.name are bound together. This means that changing either listOfSubjectName.name in JavaScript or the value in the control will automatically update the other. If listOfSubjectName.name is set to 0, then that specific item should be selected.

The listOfSubjectName variable is an array where its name property must be assigned one of the objects within it. You can modify this by updating the code below:

$scope.listOfSubjectName = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
// The default selected value is $scope.listOfSubjectName[0], but you can change it to $scope.listOfSubjectName[1]
$scope.sub_name= $scope.listOfSubjectName[1];
// Add the selected subject name into the FacultyName array
$scope.listOfFacultyName=[{
    name: 'Select Faculty',
    value: '',
    currentsubjectName:$scope.sub_name,
}]

Make sure to review the HTML section below for proper implementation:

<select id="coy" name="coy" class="form-control" ng-model="fac_name.currentsubjectName" ng-options="fac.name for fac in listOfFacultyName track by fac.value">

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

Is there a way to ensure that the await subscribe block finishes before moving on to the next line of code?

My goal is to utilize the Google Maps API for retrieving coordinates based on an address. In my understanding, using await with the subscribe line should ensure that the code block completes before moving on to the subsequent lines. async getCoordinates ...

Is there a way for me to replicate the reloading problem that occurs when a button is clicked within an HTML

Recently, I encountered a problem with our company's Web product where pressing a certain button resulted in the entire page being reloaded. This issue reminded me of a similar situation described on this website. Following the solution provided there ...

Troubleshooting the Height Problem in Material-UI's Menu

I am trying to make the menu height responsive by setting it equal to the window height using CSS. I want the menu height to increase as the page length increases due to added elements. I have attempted using "height:100%" and "height: 100vh" in the styles ...

What is the process for saving appends to variables and converting them to PHP for storage in a database?

<html> <head> <meta charset="utf-8"> <title>Test page for Query YQL</title> <link rel="stylesheet" href="http://hail2u.github.io/css/natural.css"> <!--[if lt IE 9]><script src="http://hail2u.github.io ...

Create a basic search functionality in an Express Node.js application

Recently, I decided to work on a project to enhance my coding skills. I wanted to create a simple search functionality where the URL would be "/search/(parameter here)" and display products whose names match the parameter. After writing a middleware for t ...

Form Validation Using a Separate Function

Currently, I am utilizing the jQuery Validation plugin from http://jqueryvalidation.org/ to validate my forms. By default, the validation process is triggered when the form is submitted. However, I would like to initiate the validation when a specific func ...

The CssDependency dependency type in vue-cli@3 does not have any module factory available

After using vue-cli@3 to npm run build The system showed an error message: No module factory available for dependency type: CssDependency I have extensively searched for related solutions, but they all pertain to Angular. I also attempted the following ...

Locate the next element with the same class using jQuery across the entire document

I'm working with the following HTML: <section class="slide current"></section> <section> <div class="slide"></div> <div class="slide"></div> </section> <section class="slide"></section> ...

Tips for filling jstree with information in Grails

I am currently facing difficulties in populating a jstree within a Grails gsp. Here is what I have attempted so far (rewritten for clarity): <script> $("#treeView").jsTree(); </script> <div id="treeView"> <g:each in="${atomMa ...

Using Typescript with d3 Library in Power BI

Creating d3.axis() or any other d3 object in typescript for a Power BI custom visual and ensuring it displays on the screen - how can this be achieved? ...

How to utilize DefinePlugin in Webpack to pass NODE_ENV value

I am attempting to incorporate the NODE_ENV value into my code utilizing webpack through the use of DefinePlugin. I have reviewed a similar inquiry on Stack Overflow, but I am still encountering issues. Here is the configuration I am working with: In pac ...

Error in Express Post Request: Headers cannot be modified after being sent to the client

I am a beginner in Node.js and I am facing some challenges while working on an app for learning purposes. I encountered the following issue: Error: Can't render headers after they are sent to the client. I am unsure of how to resolve it. C:\Us ...

Discover the process for connecting to the 'OnOpen' listener for a uib-popover

Context: Currently working with Angular 1 and utilizing the UIB Popover control. Within the popover template, there is a text field that I want to automatically focus on whenever the popover is displayed. Unfortunately, there isn't a specific event ...

Next.js React Hydration Issue - "Anticipated a corresponding <a> within the server HTML <a>"

Currently, I am encountering a hydration error while working on my Next.js project. The specific error message that keeps popping up is: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected serv ...

Encountering invalid parameters while attempting to utilize the track.scrobble service from the Last.Fm API in a Node.js application

After successfully completing the Last.Fm authentication process following the instructions provided here, I received the session key without any issues. However, my attempts to make an authenticated POST request to the track.scrobble method of the Last.Fm ...

google maps traffic layer with the exact time stamp

Is there a way to access the Google Maps traffic layer for specific timestamps, such as 09.01.2015 at 14:15? I am using Angular1 & the Google Maps API. This is how I currently have the traffic layer set up. Is there a way to customize it further? var tra ...

What is the best way to automatically post to Slack at regular intervals?

In order to provide users with the option to choose when they receive information from my API, such as daily at 5PM or every Friday at 5PM, I have a configuration page. Once users set their preferred time, I want to send them a Slack message at that specif ...

Discover the position of the element that was clicked within the group of elements sharing the

Here is my HTML code: <input type="button" class="buttonclose marleft fleft clrPric" value="X"> <input type="button" class="buttonclose marleft fleft clrPric" value="X"> <input type="button" class="buttonclose marleft fleft clrPric" value= ...

Clicking on React Js reverses an array that had previously been unreversed

My issue involves an array pulled from a database that I have reversed so that the newest entry is displayed at the top when a button is clicked, opening a modal-style window. However, when the array is displayed in the modal window, it appears to be flipp ...

Navigating with useRouter().push() from the "next/navigation" package is not functioning as expected when used on a customized signIn page alongside next-auth

Upon logging in successfully on my custom signIn-Page using next-auth, I am facing an issue with redirecting back to the callbackUrl. The setup includes react 18.2.0, next 13.4.8-canary.2, and next-auth 4.22.1. The code for the signIn-Page (\src&bsol ...