Refine Your Search Findings

I have a code snippet that enables searching items from a dropdown menu with a search bar, but now I want to remove the dropdown and only keep the search functionality. How can I modify the code to separate the select feature from the independent search function? Below is the code snippet:

Javascript:

// AngularJS

var app = angular.module('app', []);

app.controller('ListCtrl', function ($scope) {
    $scope.items = [{
        'name': 'Item 1'
    }, {
        'name': 'Item 2'
    },
    ...
    {
        'name': 'Item 20'
    }, ];
});

// jQuery
$('.dropdown-menu').find('input').click(function (e) {
    e.stopPropagation();
});

HTML:

 <div class="dropdown dropdown-scroll" ng-app="app">
    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">Select <span class="caret">    </span>
    </button>
    <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1" ng-controller="ListCtrl">
        <li role="presentation">
            <div class="input-group input-group-sm search-control"> <span   class="input-group-addon">
                    <span class="glyphicon glyphicon-search"></span>
</span>
                <input type="text" class="form-control" placeholder="Query" ng-model="query"></input>
            </div>
        </li>
        <li role="presentation" ng-repeat='item in items | filter:query'>     <a href="#"> {{item.name}} </a>
        </li>
    </ul>
</div>

CSS:

.dropdown.dropdown-scroll .dropdown-menu {
    max-height: 200px;
    width: 60px;
    overflow: auto;
}
.search-control {
    padding: 5px 10px;
}

Explore JSFiddle Link Here

Answer №1

Initially, you can display only one input field on the view. When a user queries, filtered options will be shown to the user. When the user selects an option, all other options will be hidden. This functionality mimics Typehead. Here's how you can update your template:

<div class="body-container" ng-app="app">
  <div ng-controller="ListCtrl">
    <div class="input-group input-group-sm search-control"> 
      <span class="input-group-addon">
      <span class="glyphicon glyphicon-search"></span>
      </span>
      <input type="text" class="form-control" placeholder="Query" 
        ng-model="query" ng-change="queryUpdated()" />
    </div>
    <div class="items" ng-hide="isSelected">
      <p class="search-items" ng-click="selectItem(item.name)" 
       ng-repeat='item in items | filter:query track by $index'> {{item.name}}
      </p>
    </div>
  </div>
</div>

In addition to your existing controller code, add these two functions:

$scope.selectItem = function(selected) {
    $scope.query = selected;
    $timeout(function() {
      $scope.isSelected = true;
    });
}
$scope.queryUpdated = function() {
    $scope.isSelected = false;
}

This setup allows for Typehead-like functionality and flexibility to adjust behavior based on requirements like showing the list initially or when users are unaware of available options.

View Working jsfiddle Example

You can also achieve the same using the Angular UI Bootstrap plugin library:

<input type="text" ng-model="selected" 
uib-typeahead="item.name for item in items | filter:$viewValue | limitTo:8" 
class="form-control">

The uib-typehead directive from the library simplifies adding dropdown templates and handles animations using ngAnimate.

See Working Plunker Example

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

What is the procedure for initiating a POST request when the payload is ready for submission?

After a successful payment, my success page is displayed with a URL that includes a query parameter. I want to make a POST request to my API endpoint when the page loads, but I'm encountering an issue where the first POST request is empty (router.quer ...

Scrolling vertically using window.open functionality

I am trying to open a pop-up window using window.open. I would like the scrollbars to appear only if necessary. Unfortunately, in Safari, the scrollbars do not show up unless I include scrollbars=1 in the code. However, this also causes horizontal scrollb ...

Processing an HTML form submission with the help of PHP and AJAX

Having trouble saving basic email data from a website to a MySQL database. I've written the code, but it's not functioning correctly and I can't seem to figure out why. <form class="subfield"> <input type="text" id="em ...

After a group of floated items, there will be an automatic "clear: both" applied

Within my Content Management System, I have custom Elements that need to be floated next to each other. Instead of adding an extra div with a class of "clear", I want to automatically insert a clear: both at the end using CSS3. I attempted this workaround ...

Assistance required with an Ajax request to display multiple dropdown menus

I must confess that my knowledge of Ajax and XML is more limited than my understanding of jQuery. My current project involves creating a user-friendly search form where the OPTION tags for each state and city SELECT are pulled from the same XML file using ...

Arranging elements within a complex div structure

I have been working on styling this div that displays the products for an e-commerce website. I initially used CSS and a table within it, but it seems like using tables for content is not recommended, so I am trying to find a better solution. However, my a ...

Unable to populate TinyMCE editor in textarea through Ajax requests

I've been trying to figure this out for nearly 4 hours with no success. My form consists of a textarea and a drop-down list. The drop-down list is populated from a MySQL database. When I select an item from the drop-down, it should display the data i ...

Utilizing jQuery for asynchronous image uploading

Just started learning jQuery and I'm having trouble uploading a jpg image file using the ajax method. It seems like it's not working properly. Can anyone guide me through this process? HTML <form action="" method="POST" enctype="multipart/fo ...

Waiting for Angular's For loop to complete

Recently, I encountered a situation where I needed to format the parameters and submit them to an API using some code. The code involved iterating through performance criteria, performance indicators, and target details to create new objects and push them ...

Utilizing AJAX for showcasing the data from an XML document

Our professor gave a brief explanation of AJAX, expecting us to showcase the data from an XML file in a scrollable text area on our website. Unfortunately, I am facing issues with loading the XML file into the designated div area. Any assistance or suggest ...

Please provide pattern block links and any special characters as input

I have a promotion box where users can input text to send to administrators. Objectives I need to prevent users from inputting links and special characters. Users should only be able to input letters a-z (case insensitive) and numbers 0-9. Input is option ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...

Combining JSON Files within an AngularJS Service

I utilize a Service in my angular application to retrieve JSON data pertaining to a football team. angular.module('UsersApp').factory('SquadService', ['$http', function($http) { return $http.get('squad/squad-bourne ...

Implementing custom validation in React to dynamically enable/disable buttons

I am working on a basic form that includes 3 input fields and one submit button. The submit button is initially disabled, and each input field has its own custom validation logic using regex. I am looking for a way to enable the button only when all the ...

Unspecified outcome of Ajax array as a choice in Select

I'm fairly new to working with AJAX / JSON and I'm having trouble figuring out how to parse an AJAX array response into a <select> dropdown. Despite going through several online tutorials and attempting different approaches to return the r ...

Is it possible to align the last item in a MUI stack to the bottom?

https://i.stack.imgur.com/IsutM.png Currently, I am working on a modal component using MUI's Grid. My goal is to position the Button at the bottom of the modal. const styles = { modalBox: { position: 'absolute', top: &ap ...

utilize jQuery to load webpage with an HTML dropdown element

Querying the Campaigns: // Getting the campaigns $campaigns = $wpdb->get_results( "SELECT * FROM tbl_campaigns ORDER BY campaignID DESC", OBJECT_K ); // Displaying the Cam ...

Guide on creating an Iframe in HTML with JavaScript

Can someone help me troubleshoot why the following code isn't working to write an iframe into HTML using JavaScript? <html> <body> <script> document.write("<iframe width="560" height="315" src="https://www.youtube.com/embed/9Ow8 ...

Sending Angular Material Select Option Value for Submission

HTML: <form id="reg" name="reg" enctype="application/x-www-form-urlencoded" action="http://api.phphotspot.com/v-2/client-register" method="post"> <md-input-container class="md-block"> <label for="country">Country</label&g ...

Function in Node.js/JavaScript that generates a new path by taking into account the original filepath, basepath, and desired destination path

Is there a custom function in Node.js that takes three arguments - filePath, basePath, and destPath - and returns a new path? For example: Function Signature Example var path = require('path'); // Could the `path` module in Node be useful here? ...