I'm looking for a way to use AngularJS to automatically populate options in a second select list based on the value selected in the first select list

My current HTML and javascript code is used to fill a select box dynamically using AngularJS:

   <select data-ng-model="selectedTestAccount" data-ng-options="item.Id as item.Name for item in testAccounts">
      <option value="">Select Account</option>
   </select>

   <script type="text/javascript">
        angular.module('test', []).controller('TestCtrl', function ($scope, $http) {
            $scope.selectedTestAccount = null;
            $scope.testAccounts = [];

            $http({
                method: 'GET',
                url: '/Admin/Exams/GetTestAccounts',
                params: { applicationId: 3 }
            }).success(function (result) {
                $scope.testAccounts = result;
            });
        });
        angular.bootstrap(angular.element("body")[0], ["test"]);
    </script>

Although this works well, I now need to implement another select list to choose subjects based on the user's selection from the first select list. I plan to set up the selects and fetch data from the server like this:

   <select data-ng-model="selectedTestAccount" data-ng-options="item.Id as item.Name for item in testAccounts">
      <option value="">Select Account</option>
   </select>
   <select data-ng-model="selectedSubject" data-ng-options="item.Id as item.Name for item in subjects">
      <option value="">Select Subject</option>
   </select>
   ...
   $http({
      method: 'GET',
      url: '/Admin/GetSubjects',
      params: { testAccountId: selectedTestAccount }
   }).success(function (result) {
      $scope.subjects = result;
   });

I'm seeking advice on how to make it so that when a user chooses an option from the first select box, it triggers a database query to retrieve and populate subjects in the second select box.

Answer №1

To monitor changes in a scope variable, you can use the `$watch` function and make changes to other parts of the application within the callback.

$scope.$watch('testAccounts', function(){
  /* Update other select "model" with the latest values on success*/
});

It may be beneficial to create service(s) for handling $http requests and move them out of controller(s). Then, retrieve data from the service within the controller.

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

Creating a secure @RestController that encrypts passwords and transmits data in JSON format using Hibernate

When developing a login/registration form in AngularJS and using Spring Boot, I encountered an issue with encrypting passwords into the database. After registering a user, my code for sending data to the database looked like this: @RequestMapping(value = ...

Get the specific element at the given index from an array of elements using

I'm currently tackling a challenge with my angular e2e test project. The task at hand involves selecting the second element within an ng-repeat that has the heading "Topic - xyz" and then clicking on the button that is a sibling of this element. How s ...

Exploring the capabilities of window opener in AngularJS applications

I am facing an issue with a function that utilizes an API to redirect me to a callback URL. After this redirection, I need to execute a function in my core JavaScript. If I keep the function separate from AngularJS and use window.opener, it works fine. How ...

Creating a dynamic and interactive table with Angular and the amazing angular-responsive-tables library

I am currently working on creating a responsive table using AngularJS. To demonstrate what I am trying to achieve, I have put together an example in this fiddle: https://jsfiddle.net/loredano/xnyzaLnu/1/ <tr ng-repeat="product in products" > &l ...

What is the best way to determine the count of elements in an array that have the active property set to true?

Can anyone help me figure out the most efficient way to solve this problem? (Filter, ng-repeat, or another method?) <div>Number of active items: {{product.length}} </div> //total number of items <div>Number of inactive items: {{product.l ...

How to store data retrieved with $http.get in AngularJS into a variable

I am attempting to assign data retrieved from $http.get to a variable in my controller. $http.get(URL).success(function (data) { $scope.results = data; console.log('results within $http.get :'+ $scope.results); }); console.lo ...

What is the best way to horizontally center a div with the layout attribute set to "row"?

I am currently working with a grid composed of cards from the Angular Material library. The issue I am facing is that the cards have a fixed size, which results in extra space on the right immediately after wrapping. My goal is to eliminate this space by ...

"Firebase manages the process of sending password reset emails for users who have not yet

Upon registering with the web application, a verification email is automatically sent to new users. To ensure security, these users are unable to log in until they have verified their email. In the event that the verification link expires and a user forge ...

Updating the state using ui-router

The application consists of pages labeled as X, Y, and Z. The intended route is to navigate from page X to select details, then move onto page Y to select additional details, and finally land on page Z. I wish that upon clicking the window's back butt ...

Can a Firefox extension be developed using XUL and AngularJS?

I've been wondering about AngularJS, the framework for HTML. Interestingly, XUL (XML User Interface Language) and HTML share similar underlying processing abilities, as both can utilize JavaScript and CSS. Is it possible for AngularJS to integrate w ...

There seems to be a glitch with jQuery on my Angular.js website

I'm trying to implement Masonry.js on my website, and although I've managed to make it work, the solution feels like a messy workaround and I can't quite figure out why it's functioning (and not functioning well). The primary issues I& ...

Sending data to API using AngularJS Http Post

Upon clicking "Add new User", a modal pop-up will appear with a form containing a text field and a checkbox. However, upon clicking the create button, the data is not being posted to the API and the modal pop-up remains open without closing. I would like ...

Having trouble locating the name 'angular' in TypeScript error message

I have completed all the necessary settings, such as adding the typescript compiler in webstorm and installing tsd with npm. However, I am still encountering an error stating 'Cannot find name Angular'. tsd.json { "version": "v4", "repo": ...

Exploring Event Propagation in AngularJS

Currently, I am working on developing a web application using angularjs for the first time. A key feature that I aim to introduce is the ability for users to create a div in the main window upon clicking on an image in the menu. To achieve this functional ...

The JSON data did not fully transfer into my AngularJS application

I wrote the code to display country details, but I am only getting partial information from the JSON. I am only able to fetch the country name and population in the output. Could there be an issue with the syntax? <!DOCTYPE HTML> <html ng-app= ...

Adding a fresh element to an object array in TypeScript

How can we add a specific value to an array of objects using TypeScript? I am looking to insert the value 1993 into each "annualRentCurrent" property in the sample object. Any suggestions on how to achieve this in TypeScript or Angular? Thank you! #Data ...

Issue with ng-change in dropdown selection

It seems like this function isn't working properly and I can't figure out why. This is my view: <tr> <th>Category</th> <td> <select class="form-control" ng-model="masterlist.category_id" ng-options="c.c ...

Checkbox with editable ngGrid

After spending hours attempting to implement an editable checkbox element in a ngGrid, I encountered some issues. When I use a type=text input, everything works smoothly. However, as soon as I switch it to type=checkbox, it stops functioning properly. Des ...

Is there a way to dynamically populate select2 data in AngularJS?

In my scenario, I wanted to utilize the createSearchChoice functionality of the Select2 widget. However, I discovered that in order to achieve this, I needed to use an html input element instead of a select element, which meant I couldn't rely on ng-r ...

Troubleshooting the issue with saving and restoring state in AngularJS ui grid

I'm having an issue with the grid not saving and restoring states, even though I am using the saveState module. There are no errors in the console, everything appears to be functioning correctly, save & restore functions are being called properly, but ...