Ways to retrieve the chosen option in an Angular.js controller

When using two select elements, the options in the second select must depend on the value selected in the first select. For example, I want to populate a list of companies (in the 2nd <select>) based on a particular service chosen in the 1st <select>:

<div ng-controller="GetCompaniesByService as class">
    <select ng-options="service.name for service in class.services"  ng-model="selectedService"></select> 
    Chosen service_id: {{ selectedService.id }}
    <select ng-options="company.name for company in class.companies"  ng-model="selectedCompany"></select> 
  </div>

In order to access the current selectedService.id value from the model within the controller, you can dynamically load data via ajax from a URL like this:

$http.get('http://127.0.0.1:3000/service/'+selectedService.id)

This data can then be used to populate the options in the second <select>.

Answer â„–1

Don't forget to keep an eye on the selectedService variable in your controller scope. Start by setting the initial value of selectedService to "false", and then once the user changes the option, selectedService will be updated with the value of the selection.

As soon as selectedService is no longer "false", display the second select/option.

Your HTML :

<div ng-controller="GetCompaniesByService as companyCtrl">
    <select ng-options="service as service.name for service in companyCtrl.services"  ng-model="selectedService"></select> 
Chosen service_id: {{ selectedService.id }}
    <select ng-options="company as company.name for company in companyCtrl.companies"  ng-model="selectedCompany" ng-show="selectedService"></select> 
</div>

Your Controller :

app.controller('GetCompaniesByService',function($scope){
    $scope.companyCtrl = {};                  //initialize the companyCtrl object
    $scope.companyCtrl.services = [...];      //perform your first $http request here
    $scope.selectedService = false;
    $scope.companyCtrl.companies = function(){
        if(selectedService){
            return $http.get('http://127.0.0.1:3000/service/'+selectedService.id)
             .success(function(data){return data;})
             .error(function(error){return [];});
        }
        else{
            return [];
        }
    };
});

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

Node.js - updating the value of a exported integer variable

In my file A.js, I have defined a module-level variable called activeCount and exported it using module.exports. In another file named testA.js, I am attempting to access and modify the value of activeCount. Despite my efforts, changes made to activeCount ...

center the view on the specified element

Utilizing ReactJs, I am developing a horizontal timeline that showcases dates. For instance, there is a list of 100 elements, each containing a date and text content. The dates are displayed horizontally using flex-direction="row" and overflowX ...

Alternative names for the identical dynamic route slug in Next.js involve redirection methodology on stackoverflow platform

Currently, I am working on a project that includes links for various categories and products. The task at hand is to refactor the project using Next.js while ensuring that the existing links are preserved for SEO purposes. Here is an outline of the curren ...

Retrieving the list id during item reordering in ng-sortable

I am currently utilizing the drag and drop functionality from https://github.com/a5hik/ng-sortable to rearrange a list. My issue lies in identifying the id of the list when an item is moved between two lists. I need to determine the origin list and destin ...

Python Eve encountering WSGI issue [Errno 32] causing a broken pipe during an Ajax call

As I operate a simplistic wsgi server, from run import app if __name__ == "__main__": app.run(threaded=True, debug=True) When I send a get request to the server, it responds with a 200 message but no data. An error message is displayed: Error on r ...

JSON geometry imported is not following the movement of the bones

After importing a model into my Three.js scene, I encountered an issue where the bones can be moved and rotated successfully, but the model's geometry does not follow these bone movements. For importing the JSON file and adding it to the scene, here ...

Enhancing CKEditor: Inserting new elements upon each dialog opening

I am facing a challenge where I need to dynamically add varying numbers of elements to a dialog window each time it is opened. Below is the code I am working with: CKEDITOR.on( 'dialogDefinition', function(ev) { var dialogName = ev.data.name ...

Capture video calls in a room exclusively when the user initiates recording by pressing the record button on Twilio

My goal is to capture the video call happening between two users. The recording should start when a user clicks on the record button. However, I am encountering the following problem: Unable to fetch record↵Invalid RecordingSid parameter I am using Rai ...

Creating a Shopping Cart using Laravel and Angular

My current application features a shopping cart that works well for me, but my colleague finds it to be too "slow". I have been brainstorming ways to improve its efficiency and speed. This is the process of how my page currently loads: The Product/Ticke ...

Enhance the functionality of your Angular templates by utilizing filters to showcase object or model properties that may not be functioning

Here is what I have: // The key has the format "first.second.third"; // splitString function returns the part after the last ".". {{object.eventMap[key|splitString:'.':-1]}} is not functioning correctly. This code is within an ng-repeat, so it ...

Ways to prevent a single element from being included in the selection of the entire

Here is my question: I am facing an issue with a context menu that should only disappear when clicking outside of a specific row within that menu. The element I want to exclude, with the id "except", is buried deep within multiple parent elements in my co ...

Sending a function in React.js from one functional component to another

I'm facing an issue with my code where I have a function called postaviRutu in the App component that I need to pass to the child component Sidebar. When clicking on an element in Sidebar, I want it to call the postaviRutu function in App. I've a ...

Navigating with React to a specific endpoint does not display the expected content

When I navigate to another endpoint, the component content only shows up after manually refreshing the page. I have come across similar inquiries on various platforms such as Stack Overflow and here. I have also consulted the React Router documentation an ...

Unable to refund items in the list box

I have been working on a code snippet to retrieve a list of items from a listbox. The listbox can contain any number of 10-digit numbers in multiple rows. However, when I run the code, the "NPIListBox.Items.Count" function only returns a count of 1, even w ...

redux reducer returns an empty array after applying filter to the state

In my React component, I am utilizing Redux to manage the state. Since I am new to Redux, I have encountered some challenges with one of the reducers I created. One of the methods in my component involves making an HTTP request and then dispatching the dat ...

Guide to including user-defined headers in Angular's httpRequest

I am attempting to make an http get() request by passing some values in headers. I am currently updating the headers as follows: import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core' ...

Streamlining a menu using ng-repeat

The title of this question might be a bit ambiguous, but I'm at a loss for what else to call it. Essentially, here's my dilemma: I've set up an angular menu with submenus. Each menu item is separate, and the submenu items are being injected ...

My objective is to use JavaScript to dynamically update information in an HTML document using data retrieved from a JSON file

Experience the benefits of our membership program: PROGRAMMING var benefitsData = document.getElementById("memberBenefits"); for (var i = 0; i < membershipData.benefits.length; i++){ benefitsData[i].getElementsByTagName('h4')[0].innerHTML = ...

What steps can be taken to address an undefined error before the execution of useEffect?

Today I encountered a small issue with my online player. It's fetching songs from the database using useEffect and saving them in state like this: const [songs, setSongs] = useState([]); const [currentSong, setCurrentSong] = useState(songs[0]); a ...

Creating custom fields with user input in WordPress widgets

I'm currently working on a theme and I need to create dynamic input fields for a set of predefined labels in a custom widget. My goal is to achieve the following layout: CourseName FieldONE FieldTWO ----------------------------- ...