Reset dropdown selection when a search query is made

Currently experimenting with Angular to develop a proof of concept. Utilizing a functional plunker where selecting an option from a dropdown populates a list of items from an $http.get( ). Additionally, there is a search input that should trigger its own $http.get( ) call and display data in the same list as above. However, integrating these features seamlessly has been challenging. Ideally, users should be able to either select from the dropdown or use the search functionality, but not both simultaneously.

The following is the html code:

<html>
<head>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40212e27352c21326e2a3300716e746e706d32236e70">[email protected]</a>" data-semver="1.4.0-rc.0" src="https://code.angularjs.org/1.4.0-rc.0/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>
<body ng-app="myapp" ng-controller="MainCtrl">
  <h1>Hello Plunker!</h1>
  <div>
    <select ng-options="post as post.id for post in allPosts" ng-model="selectPost" ng-change="select()">
      <option value="">--select--</option>
    </select>
    <input type="text" ng-model="searchText" ng-change="search()" />
    <ul>
      <li data-ng-repeat="item in records | orderBy:'Name':reverse">
        {{item.email}}
      </li>
    </ul>
  </div>
</body>
</html>

And here is the Javascript snippet:

angular.module('myapp', [])
  .controller('MainCtrl', function($scope, $http) {
    var records;
    $scope.selectPost = '';
    $scope.searchText = '';
    $http.get('http://jsonplaceholder.typicode.com/posts').success(function(data1) {

      $scope.allPosts = data1;
      $scope.total = $scope.allPosts.length;
    });

    $scope.select = function() {
      $scope.searchText = '';
      $scope.search = $scope.selectPost;
      
      $http.get('http://jsonplaceholder.typicode.com/comments').success(function(data2) {
        $scope.records = [];
        data2.forEach(function(r) {
          if (r && r.postId && r.postId === $scope.selectPost.id) {
            $scope.records.push(r);
          }
        });
      });
    };

    $scope.search = function() {
      //clear the select, go here http://jsonplaceholder.typicode.com/comments
      //and display/filter emails based on the search input
    };

  });

Upon entering text into the search input, the intention is to invoke the search( ) function, reset the select input, make another AJAX call to retrieve matching email data, and populate the <li> accordingly.

Answer №1

To start, it is important to note that the line of code:

$scope.search = $scope.selectPost;

is actually causing an issue by overwriting the search function. It would be best to remove this line entirely.

Instead, in the search function, consider resetting the select element and filtering the results based on email rather than ID.

For a visual example, you can check out the following link: http://plnkr.co/edit/BU3s1aNS8b0ChT29D2J5?p=preview

Answer №2

Avoid declaring the variable $scope.search twice

Consider changing the function name $scope.search to something else, like:

HTML:

<input type="text" ng-model="searchText" ng-change="tsearch()" />

Angular:

      $scope.tsearch = function() {
          //clear the select
          $scope.selectPost = '';

          $scope.search = $scope.searchText;
          $http.get('http://jsonplaceholder.typicode.com/comments').success(function(data2) {
              $scope.records = [];
              data2.forEach(function(r) {
                  if (r && r.postId && r.postId === $scope.selectPost.id) {
                      $scope.records.push(r);
                  }
              });
         });
    };

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

Injecting a service into an Angular constant is a straightforward process that involves

Is it possible to define a constant that utilizes the $locale service? Since constants are objects, injecting them as parameters like in controllers is not an option. How can this be achieved? angular.module('app').constant('SOME_CONSTANT&a ...

The download of package-lock.json is not initiated for a linked GitHub URL

I currently have two projects on GitHub. One is named "mylibrary" and the other is "test-project." In my "test-project," I have linked "mylibrary" using its GitHub URL in the package.json file as shown below. dependencies: { "mylibrary": "git+ssh://& ...

What is the significance of a listener signaling an asynchronous response with a return of true, only to have the communication channel close before the response could be received?

Currently, I am developing a React application that involves the use of various npm modules. One of these modules is a self-built NPM package called modale-react-rm (available at this link). This package serves as a simple modal component that utilizes the ...

What is the significance of combining two arrays?

const customTheme = createMuiTheme({ margin: value => [0, 4, 8, 16, 32, 64][value], }); customTheme.margin(2); // = 8 This code snippet showcases how to define spacing values in a Material-UI theme configuration. For more details on customization re ...

Utilizing Node.js and Express to transmit numerous JSON variables from server to client using response.send()

I am currently in the process of developing a nodejs search application using the itunes-search library to retrieve software information from my local database. I am utilizing the express framework for this purpose. The search module returns details such a ...

Is there a way for me to acquire the Amazon Fire TV Series?

I'm currently working on developing a web app for Amazon Fire TV, and I require individual authorization for each app. My plan is to utilize the Amazon Fire TV serial number for this purpose. However, I am unsure how to retrieve this serial using Jav ...

Guide on redirecting to a specific Vue-app page using Flask

I am currently working on an application that includes a page that ends with '@' and provides meta information for the page without '@'. For example, if the page '/user/aabb' contains information about the user 'aabb&apos ...

A guide on retrieving JSON data from a PHP server to an Android mobile device

I have a mobile application that needs to retrieve JSON data from a PHP web server. The URL I have gives me the following JSON data: {"items":[{"latitude":"420","longitude":"421"}]}. My goal is to extract the latitude and longitude values from this JSON fo ...

Changing a button's text in Vue.js when holding a keyboard modifier - how to do it!

While working with Vue, I am attempting to modify a button's behavior when the Shift key is pressed. Adjusting the behavior of the click event was straightforward: @click.exact="goForward" @click.shift="goBackward" However, I am f ...

Difficulties accessing MongoDb database using Node.js

Having issues when trying to read this data collection using mongoose and Node.js: I have a single JSON object within my Collection and I'm attempting to access it with the following code: materias.find().exec(function(err1,materias){ if(err ...

What can we expect from the behavior of a localhost Express app with an Aurelia/Angular Admin Panel?

Currently, I am working on a Web Project that utilizes Express to serve the website and an Aurelia (or any Framework) App as an Admin Panel for editing the content. The Aurelia-App is being served through the static/public directory of Express, with the co ...

Navigating HTML with Node.js and Express.js

I have been working on routing multiple HTML pages in my project. The index.html file loads without any issues, but when I try to load raw.html, an error message pops up: Error: Failed to lookup view "error" in views directory Below is part of my app.j ...

Working with arrays containing numerical keys in JSON using jQuery

If I have a PHP file that generates JSON data with numerical keys like this: <?php $array[1] = "abcd"; $array[2] = "efgh"; $array[3] = "1234"; $array[4] = "5678"; echo json_encode($array); ?> How can I access the value associated with key 4? The i ...

Guide to sending a post request with parameters in nuxt.js

I am trying to fetch data using the fetch method in Nuxt/Axios to send a post request and retrieve specific category information: async fetch() { const res = await this.$axios.post( `https://example.com/art-admin/public/api/get_single_cat_data_an ...

Attempting to determine the number of elements in a JSON array

Having an issue with counting the length of an array converted from JSON using json_decode in PHP. The current code is not returning the expected results. The JSON list consists of an array with 10,000 items but something seems to be missing. Any assistanc ...

Rotate images using a JQuery plugin without using HTML tags, solely through passing the images in JavaScript

I am currently working on creating a jQuery image rotator from scratch. While I know there are simple jQuery sliders/rotators available, I specifically want to include the image files directly within the JS code. I do not want to use this HTML structure: ...

Tips for removing a row from a table

I've been working on a responsive data table where each time I click an add button at the end of a row, a new row is added with the add button turning into a delete button. Below is the code I've implemented: The Table: <table id="invoice_ta ...

Utilizing the Java Script SDK for Facebook API to Publish Actions

I've been encountering difficulties with the Facebook API. I have created an app, an object, and an action, and I'm trying to test publishing in my stream (I understand that public publishing needs authorization from Facebook, but as an administr ...

Manipulating cursor position in React's contentEditable

I created a simple component class ContentEditable extends React.Component { constructor(props) { super(props); this.handleInput = this.handleInput.bind(this); } handleInput(event) { let html = event.target.innerHTML; if (this.props. ...