Updating the search list in md-autocomplete based on the input from another md-autocomplete in AngularJS

I am in need of assistance with updating the search list of my second <md-autocomplete> drop-down based on the selection made in the first drop-down.

You can take a look at an example plunker which is not currently functioning properly: http://plnkr.co/edit/GxQujjAcxYdawlANJd9O?p=preview

Desired behavior:
When a user selects, for instance, "This is an A" from the first drop-down, I want to update the options to $scope.numbersA, which would be [1, 2, 3]. Similarly, if someone chooses "This is a B", then the corresponding number array would be $scope.numbersB, and so on.

I have been struggling to make this functionality work as intended. In my application, there is an $http request triggered for every change in the first drop-down. As mentioned on this Stack Overflow post, I am using .then() instead of .success(). The plunker example has been simplified due to less code complexity :)

Edit: Please note that there is an issue with the searchText function in the plunker, but it functions correctly in my actual application.

Answer №1

To ensure that the search handler is triggered each time the user enters a value in the second autocomplete, use the attribute md-no-cache.

Pass the selected value from the first autocomplete as an argument to the search handler of the second autocomplete.

Here's an example:

// JavaScript code snippet
var app = angular.module('app', ['ngMaterial']);

app.controller('ctrl', ['$scope',
  function($scope) {
    $scope.letters = [{
      'display': 'This is an A',
      'value': 'a'
    }, {
      'display': 'This is a B',
      'value': 'b'
    }, {
      'display': 'This is a C',
      'value': 'c'
    }];
    $scope.numbersA = [1, 2, 3];
    $scope.numbersB = [4, 5, 6];
    $scope.numbersC = [7, 8, 9];

    $scope.getMatchesLetter = function(query) {
      if (query === null || query === "" || query === undefined)
        return $scope.letters;

      var results = query ? $scope.letters.filter(createFilterFor(query)) : $scope.letters;
      return results;
    };

    $scope.getMatchesNumber = function(query, selected) {
      var arrToSearch;
      switch (selected.value.toUpperCase()) {

        case 'A':
          arrToSearch = $scope.numbersA;
          break;

        case 'B':
          arrToSearch = $scope.numbersB;
          break;

        case 'C':
          arrToSearch = $scope.numbersC;
          break;

      }
      if (query === null || query === "" || query === undefined)
        return arrToSearch;

      var results = query ? arrToSearch.filter(createFilterFor(query)) : arrToSearch;
      return results;
    };

    $scope.itemChange = function(item, whichOne) {
      switch (whichOne) {
        case 'A':
          $scope.numbersA = item;
          break;
        case 'B':
          $scope.numbersB = item;
          break;
        case 'C':
          $scope.numberC = item;
          break;
      }
    };

    function createFilterFor(query) {
      var lowercaseQuery = angular.lowercase(query);
      return function filterFn(state) {
        //return (state.value.indexOf(lowercaseQuery) === 0); // startsWith()
        return (state.value.search(lowercaseQuery) != -1); // contains()
      };
    }

  }
]);;
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>


  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/0.11.2/angular-material.min.css">
  <script src="script.js"></script>
</head>

<body ng-app='app' ng-controller='ctrl'>
  <md-autocomplete md-selected-item="selectedItemLetter" md-search-text="searchTextLetter" md-selected-item-change="itemChange(item)" md-items="item in getMatchesLetter(searchTextLetter)" md-item-text="item.display" md-min-length="0" placeholder="Select letter">
    <md-item-template>
      <span md-highlight-text="searchTextLetter">{{item.display}}</span>
    </md-item-template>
    <md-not-found>No matches found.</md-not-found>
  </md-autocomplete>

  <br>
  <br>

  <md-autocomplete md-selected-item="selectedItemNumber" md-search-text="searchTextNum" md-selected-item-change="itemChange(item)" md-items="item in getMatchesNumber(searchTextNumber,selectedItemLetter)" md-no-cache="true" md-item-text="item" md-min-length="0"
  placeholder="Select number">
    <md-item-template>
      <span md-highlight-text="searchTextNumber">{{item}}</span>
    </md-item-template>
    <md-not-found>No matches found.</md-not-found>
  </md-autocomplete>
</body>

</html>

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

Utilizing dropzone.js with asp.net Web Forms

Is it possible to retrieve the image properties (such as height and width) after uploading a file using dropzone.js in an .aspx application, in order to perform client-side animations? Javascript $(document).ready(function () { $(".dropzone").dropzon ...

In a React application, the input field unexpectedly loses focus after typing just one character

Has anyone encountered an issue with a dropdown menu causing input field focus to be lost after typing one character? I've attempted setting unique keys for each field, but it hasn't resolved the problem. For reference, here is the link to the p ...

How can I effectively display personalized information from an MSAccess database on a WordPress website?

I am seeking advice from experienced Wordpress developers. My organization possesses an internal MS Access database that comprises various tables, reports, and input forms. The structure of the database is relatively straightforward, encompassing informati ...

Submit form data asynchronously using Ajax and serialize the form data before posting

I'm currently facing an issue with posting HTML form values in my code. Everything works fine except for the fact that I can't get it to post single quotes ' . I believe this problem is caused by the usage of serialize. I've attempted c ...

Storing Tags with jQuery Tag-it: A guide to saving user inputted tags in an object

Recently stumbled upon a fantastic plugin called tagit, and now I'm looking for a way to extract tag values from it and convert them into an object. Any assistance on this matter would be greatly welcomed! ...

Using JavaScript to pass a variable into a Promise

I am currently working on a project in EmberJS that involves making an Ajax request to fetch information and then resolving based on a specific part of the response that may vary. return new Promise((resolve, reject) => { const { resourceName, i ...

How can elements be collapsed into an array using the Reactive approach?

Consider this TypeScript/Angular 2 code snippet: query(): Rx.Observable<any> { return Observable.create((o) => { var refinedPosts = new Array<RefinedPost>(); const observable = this.server.get('http://localhost/ra ...

The db.all method does not provide an array as its return variable

Seeking to extract an array from the db.all function to incorporate it into a custom JSON object for a response. Various attempts have been made including using Object.values(members), members.fulfillmentValue, and some PROMISE methods discovered on Stack ...

What is preventing my content from showing up when clicked like this?

I have created a javascript script to reveal hidden content, but for some reason it is not working when I click on it. Can anyone provide assistance? Below is the script I am using: <script src="style/jquery/jquery.js"></script> <script> ...

Execute JavaScript function after completion of CSS animation using jQuery

I'm working on an accordion feature that uses CSS animation to expand the clicked item. The expansion is triggered by li:target. However, I'm facing an issue where when clicking on an item, the scroll position doesn't align correctly with t ...

Challenges with JavaScript setInterval

Hello everyone! I'm currently working on running a loop with setInterval, but I want each element in the array to use a random interval instead of the entire array doing so. Below is the code I have been using: setInterval(function() { for ( ...

Error encountered: Unexpected token when defining inline style in React

When attempting to prevent scrolling on the page by using style='overflow-y: auto;': render() { return ( <div style={{overflow-y: auto}}> <div>{this.props.title}</div> <div>{this.props.children}& ...

Angular template not refreshing automatically

Within my controller: $scope.deleteUser = function(user){ $.ajax({ url: "/users/" + user.id.toString(), method: "DELETE", success: function(result){ $scope.users = result["users"]; ...

Use the map function to find the highest number within each array

function each(collection, func) { if (Array.isArray(collection)) { for (var i = 0; i < collection.length; i++) { func(collection[i], i); } } else { for (var key in collection) { func(collection[key], key); } } } functi ...

Exploring how RequireJS and AngularJS services communicate with the controller

RequireJS and AngularJS. I am encountering an error when trying to access the controller inside a service. The error message I receive is: 'Argument 'onCloseAlert' is not a function, got undefined.' This service is being called by an ...

Managing JavaScript events in the console

Running a server for a video game in node.js where the console communicates with clients via websockets. I have a function to spawn enemies from a MySQL database, but I am encountering an error that seems to be related to a jQuery script... I want the scr ...

showing the values stored in local storage

My goal is to show only the values stored in local storage, excluding the key value that displays all data after submitting the login form. welcome <span id="demo"></span>; <script> document.getElementById('demo').innerHTML = ...

Utilizing a function from a separate file in Vue: A step-by-step guide

Recently starting to work with Vue, I encountered an issue while trying to utilize a helper function called arrayDateFormatter within one of my imported .vue files. Despite importing it, the function doesn't seem to be called when used inside the moun ...

Generate an HTML dropdown menu based on the item selected from the autocomplete input field

I have a PHP page that searches the database and returns JSON results to an autocomplete input field: https://i.sstatic.net/PPFgR.png When I display the response from the PHP file (as shown above), it looks like this: { "success": true, "results ...

ReactJS not displaying the class effect as intended

When using the react zoom pan pinch library, I am trying to set the height to "100%" for TransformWrapper and TransformComponent. Interestingly, it works perfectly fine when done through Chrome inspect, but when attempting to add a className or use style={ ...