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

Express Node.js Error: Address Information Syntax Issue

While developing my server using TypeScript for my Angular app to connect to, I encountered an issue when trying to run the code snippet below. It seems that Node.js or TS is not yet compatible with certain ES6 features like destructuring with AddressInfo, ...

Rename multiple files in bulk

With 10000 files consisting of php, html, css, and png formats that are interconnected to operate the website's engine, I am looking for a way to perform bulk renaming in order to ensure proper functionality. Not only do I need to rename the actual fi ...

Obtaining a complex object from a Checkbox set in AngularJS through the use of ngModel

Hey there! I've been searching on Stack Overflow regarding this topic, but I haven't found a solution that matches exactly what I need. If you want to take a look at the code, here is a JSFiddle link for reference: http://jsfiddle.net/gsLXf/1/ ...

Issues persist with redirection when using AJAX and PHP in a login form, resulting in the user staying on the index page

After filling out both the email and password form fields and clicking the sign-in button, my script is functioning correctly. However, upon clicking the sign-in button, I want the user to be redirected to the home page. Currently, the user remains on the ...

Leverage backend data in Angular-Google-Chart without the need for AJAX requests

I am attempting to transfer chart row data from a text field in HTML. For some unknown reason, I am unable to connect the model to controller SecondCtrl. The following code is a modified version of this http://plnkr.co/edit/3RJ2HS?p=preview from https:// ...

Importing a file using its absolute path in JavaScript

Within the dependencies directory, there exists a module named foo: import foo from '../dependencies/foo'; // This import statement works as intended The challenge arises when attempting to import from a different path due to deployment in an AW ...

Webpack dynamically imports files from a folder

In order to streamline my development process, I have a specific structure for organizing React components. Each main component has its own components folder right alongside it. Currently, I find myself manually importing each component from the components ...

Display thumbnail images in jquery-ui dropdown menu

Hello, I'm looking to display a small image (the user's thumbnail) on the jquery-ui dropdown by making an ajax call. As someone new to ajax and unfamiliar with jquery-ui, I would appreciate some guidance in the right direction. Thank you! HTML/J ...

Best practices for managing user authentication

After researching different approaches to incorporating authentication into an Angular app, I opted for utilizing Firebase Simple Login as a (No-)Backend solution. I want my app to display content only to logged-in users. When users are logged out, they s ...

Transfer a file to Amazon S3 using the Microsoft Office Add-In

I am working on developing a JavaScript Microsoft Office add-in that allows users to save a document to an S3 bucket. However, I have not been able to find a way to achieve this. Has anyone managed to successfully make this work before? ...

Having trouble deleting multiple rows with ng-repeat in datatables

Having followed the instructions in this post, I quickly integrated it with jquery datatables. However, the functionality is not as expected. When attempting to delete rows, they do not get deleted. Furthermore, if I navigate to the next page and return, ...

Using CSS or Javascript, you can eliminate the (textnode) from Github Gist lists

My goal is to extract the username and / values from a series of gists on Github Gists. The challenge lies in the fact that there are no identifiable classes or IDs for the / value. https://i.stack.imgur.com/9d0kl.png Below is the HTML snippet with a lin ...

Quasar unable to detect vuex store

I am currently working with the Quasar framework and I am trying to add a store module. Despite running the quasar new store <name> command, I keep receiving the message "No vuex store detected" in the browser console. Any idea where the issue migh ...

Dynamic sliding box jumps instead of simply fading in/out

My app features both a navigation bar and a sub-navigation bar. Within the sub-navigation bar, users can click on a button that triggers the appearance of another sub-bar while hiding the original one. The new sub-bar should smoothly slide out from behind ...

How can we eliminate all elements from jQuery except for the first and second elements?

HTML <div class="geo_select"> <h3>header 3</h3> in Above HTML code i want to remove all element except <h3> and default content<div> inside the <div class='geo_select'> in jquery.. How to remove all ...

Sorting WordPress entries by nearby locations

I have WordPress posts that are being displayed on a Google Map. The posts are pulling data from a custom post field that contains the latlng value, where latitude and longitude are combined into one. Additionally, the map shows the user's location u ...

Accessing data from localhost using Vue.js and Axios is restricted due to CORS policy and the error "Access to XMLHttpRequest" may be

Having a minor issue... Trying to retrieve a basic json file from my server for testing purposes (not an actual API). Utilizing VueJS and axios. Here is my code : getServicesAPI() { axios.get("http://51.91..../dist/API/Services.json").the ...

Taking steps when a number is enclosed within a span

Testing a simple code with similar action to what I want. Apologies for any language errors, hoping to be understood :-) The HTML code snippet: <div class="pagination"> <a href="#" class=""><span>1</span></a> <a href=" ...

It is advised not to use arrow functions to assign data when fetching API data with axios in Vue.js 2

Trying to retrieve data from a URL using Axios in my Vue app is resulting in the error message: Error: Arrow function should not return assignment Complete error message: Error: Arrow function should not return assignment (no-return-assign) at src\co ...