Using a web service to retrieve data, dynamically populating a second dropdown menu based on the user's selection from the first dropdown

Utilizing a web-service named KeywordService that interacts with the .NET controller, I have successfully populated a drop-down by fetching a list from another project.

In the angular controller below, I have been advised by our web developer to monitor the keyword change event and pass the keyword to the getQualifier function. How can I achieve this monitoring? Can someone guide me on how to do it?

var StockItemMultiMillInquiryController = function ($scope, $sce, $rootScope, $modal, $window, StockItemMultiMillService, KeywordService, QualifierService) {

$rootScope.title = 'Stock Item Multi Mill Inquiry';
$scope.allMills = [];
$scope.mill = '';
$scope.stockNumber = '';
$scope.description = '';
$scope.qtyonhand = '';
$scope.qualifier = '';
$scope.costType = '';
$scope.keyword = '';
$scope.allKeywords = [];
$scope.qualifier = keyword;
$scope.selectedQualifier = '';
$scope.allQualifiers = [];

KeywordService.getKeyword().then(function (keywords) {
    $scope.allKeywords = keywords
});

QualifierService.getQualifier().then(function (qualifier) {
    $scope.allQualifiers = qualifier
});

Below is the service:

// Keyword service for dropdown ticket #54507
app.service('KeywordService', function ($http, cache) {
   return {
    getKeyword: function () {
        var keywords = cache.get('keyword');
        if (!keywords) {
            return $http({ method: 'JSONP', url: "/api/core/keyword/keyword?callback=JSON_CALLBACK", params: {} }).then(function (result) {
                if (result.data.success) {
                    cache.put('keyword', result.data.data);
                    return result.data.data;
                } else {
                    return [];
                }
            });
        } else {
            var deferred = $q.defer();
            deferred.resolve(keywords);
            return deferred.promise;
          }
       }
    };
});

// Qualifier service for dropdown ticket #54507
 app.service('QualifierService', function ($http, cache) {
    return {
      getQualifier: function () {
        var qualifiers = cache.get('qualifier');
        if (!qualifiers) {
            return $http({ method: 'JSONP', url: "/api/core/qualfier/qualifier?callback=JSON_CALLBACK", params: {qualifier: qualifier} }).then(function (result) {
                if (result.data.success) {
                    cache.put('qualifier', result.data.data);
                    return result.data.data;
                } else {
                    return [];
                }
            });
        } else {
            var deferred = $q.defer();
            deferred.resolve(qualifiers);
            return deferred.promise;
        }
       }
    };
 });

The ASP.NET controller responsible for handling keyword and qualifier requests:

Imports PCA.Core.Search
Imports PCA.Core.Web.JSON

Public Class KeywordController
   Inherits System.Web.Mvc.Controller

' GET: /Plants
<PCA.Core.Web.CompressionFilter> _
Function Keyword(callback As String) As ActionResult {
    // Controller implementation details here...
}

End Class

Imports PCA.Core.Search
Imports PCA.Core.Web.JSON

Public Class QualifierController
     Inherits System.Web.Mvc.Controller

' GET: /Plants
<PCA.Core.Web.CompressionFilter> _
Function Qualifier(callback As String, keyword As String) As ActionResult {
    // Controller implementation details here...
}

End Class

The ViewModel classes for Keyword and Qualifier:

Namespace ViewModels.Core

Public Class Keyword {
    // ViewModel class for Keyword 
}

End Namespace

Namespace ViewModels.Core

Public Class Qualifier {
    // ViewModel class for Qualifier
}

End Namespace

And finally, the HTML file containing the dropdown selections:

<!DOCTYPE html>
 <!--  View for the Stock item multi mill inquiry Ticket #54507-->
 <html>
 <head>
     <title>Stock Item Multi Mill Inquiry</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta charset="utf-8>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<div class="row ">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
        // Dropdown menu options here...
    </div>
</div>

Answer №1

If you want to trigger an action when the select box value changes, you can make use of the ng-change attribute.

ng-change="getQualifier(keyword)"

To pass the model from the first select to the second one, you can do something like this:

<select class="btn btn-info dropdown-toggle" style="width: 92%" ng-model="keyword">
    <option value="">Select a Keyword</option>
    <option ng-repeat="keyword in allKeywords" value="{{keyword.description}}"> {{keyword.description}} </option>
</select><br/><br/>

<select class="btn btn-info dropdown-toggle" style="width: 92%" ng-model="selectedQualifier" ng-change="getQualifier(keyword)">
    <option value="">Select a Qualifier</option>
    <option ng-repeat="qualifier in allQualifiers" value="{{qualifier.description}}"> {{qualifier.description}} </option>
</select>

I hope this helps you achieve what you're looking for!

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

Tips for concealing text in ion-option ionic2

Is there a way to hide text within an ion-option? I'm looking to conceal or remove certain text from displaying in an ion-option without deleting the underlying data. This is important as I want users to be able to choose it. <ion-select [(ngModel ...

Parent method instantiating child class instance

My code includes a parent class and a child class, with the parent class containing a modify function: const modify = (data) => { const newData = data // changes newData in some way return newData } class Parent { constructor(data) { this.d ...

Stop the user from navigating away from the current page if any changes have not been saved, all within React without relying on

My project includes a panel that opens as a modal from right to left. This panel contains a left navigation menu with various options that, when clicked, display different components. These components primarily consist of forms, and my goal is to alert th ...

What is the reason behind $('#id').val() not functioning properly when document.getElementById('id').value is working flawlessly?

$('#id').val() = $.cookie("name"); - does not function as expected, no changes occur document.getElementById('id').value = $.cookie("name"); - works properly What is the reason behind this inconsistency? ...

"Encountered an undefined error with the title property of this.state.project in the Wordpress API

I'm currently working on a project that involves a Backend Wordpress and a front-end React setup. However, I've encountered an issue when attempting to retrieve the title.rendered from the JSON Data. This error is displayed: TypeError: this.sta ...

The Highchart is failing to display a single data point

The marker I set is not displaying when there is only a single data point available. The data point is only showing up when we hover on the chart. Check out an example fiddle here - jsfiddle ...

Using ng-repeat within another ng-repeat allows elements to be displayed as siblings

My goal is to create a structured list using angularjs: Parent 1 Group1 Child1 Child2 Child3 Child4 Group2 Child1 Child2 Parent 2 Group1 Child1 Child2 Group2 Child1 I have data organized in a similar format like this. $scope.parents = [{ name:&apos ...

Mapping an array of objects using dynamically generated column names

If I have an array of objects containing country, state, city data, how can I utilize the .map method to retrieve unique countries, states, or cities based on specific criteria? How would I create a method that accepts a column name and maps it to return ...

Tool to stop automatic logouts on websites

In the web application where I work, users are automatically logged out after a period of inactivity. Unfortunately, I am unable to control this feature. The code responsible for logging the user out is as follows: var windoc = window.document; var timeou ...

Problem with deploying a Nextjs project on cPanel

I've been struggling to deploy a nextjs project on cPanel. The project consists of only one SSG page. I set the basePath in next.config.js to deploy the project, but I keep getting a 404 page not found error and the page keeps getting called in the ne ...

Issue with Showing Hidden Section using Jquery - Try it Out on JSfiddle!

I'm struggling with a script that should reveal a hidden <div> when a checkbox is clicked. Despite my best efforts, I can't seem to get the section to display correctly. The snippet of code in question looks like this... If you'd like ...

Moving away from the ng-route and transitioning to the ui-router for AngularJS navigation

I'm just starting out with AngularJS and I'm a bit confused about how to implement angularjs ui-router in the following scenario: The scenario involves two main sections. The first section is the Homepage, which includes login and sign-up views, ...

Use jQuery to dynamically capture and store the value of data-rowindex into an array

Is there a way to dynamically store the data-rowindex value into an array? <tr class="ewTableRow" data-rowindex="1" id="r1_assessment_training" data-rowtype="2"> Below is the code I've attempted. Not entirely sure if it is the correct approach ...

The rollup-plugin-typescript is unable to identify the 'lib' option within the 'compilerOptions'

Currently, I'm following a tutorial on how to create an npm package. The tutorial can be found here. Here is the content of my tsconfig.json file: { "compilerOptions": { "target": "es5", "module": "es2015", "sourceMap": tr ...

"Exploring the functionality of Angular directives' link function

Just starting out with Angular and delving into directives. While working on my directive's link function, I noticed that when I log my element, it shows up as an array. This raised the question in my mind - why is it an array? <mouse-enter>HI& ...

utilizing Typescript object within an array of objects

How can I optimize typing this nested array of objects? const myItem: Items[] = [{ id: 1, text: 'hello', items: [{ id: 1, text: 'world' }] }] One way to approach this is by using interfaces: interface It ...

Different ways to showcase the local time zone

Currently, I am utilizing datetimepicker.js. The code snippet that I am using is shown below: Partial HTML: <div ng-hide="editingData[x.date]">{{x.date|date}} </div> This results in the following date format: May 21, 2015 2:52:29 PM Desir ...

Difficulty Encountered in Rendering Component Using setTimeout Function

Having trouble figuring out why my component, enclosed in a setTimeout function, is not appearing on the DOM: const ContentMain = Component({ getInitialState() { return {rendered: false}; }, componentDidMount() { this.setStat ...

Unlocking the potential of Node.js: Mastering the art of passing extra parameters in async

Exploring JavaScript and Node.js I'm currently working on developing some javascript / node.js code with a specific purpose in mind: To retrieve keys from a redis database and extract relevant information from the hash. Here is an example of what ...

The issue with the angular-ui ui-calendar is that it does not reflect changes made to the Event Source Object or

I implemented fullcalendar.js into my angular app using angular-ui / ui-calendar. (angularjs 1.3.10, fullcalendar 2.2.6, ui-calendar 0.9.0-beta.1, jQuery 2.1.3, moment 2.9.0 & angular-moment 0.9.0) Within the calendar, I utilize the dayClick functio ...