AngularJS Autocomplete Widget

Currently, I have implemented a popup in angularjs along with a form. To enhance user experience, I have integrated an auto-completer feature using the following directive:

portfolio.directive('auto', function($timeout) {
    var names = ["john", "bill", "charlie", "robert", "alban", "oscar", "marie", "celine", "brad", "drew", "rebecca", "michel", "francis", "jean", "paul", "pierre", "nicolas", "alfred", "gerard", "louis", "albert", "edouard", "benoit", "guillaume", "nicolas", "joseph"];

    return {
        restrict : 'A',
        require : 'ngModel',
        link : function(scope, iElement, iAttrs) {
            iElement.autocomplete({
                source: names,
                onSelect: function() {
                    $timeout(function() {
                      iElement.trigger('input');
                    }, 0);
                }
            });
    }
    };
});

The functionality is working as expected, however, there is an issue where the autocomplete box appears behind the popup. Does anyone have any suggestions on how to resolve this?

Answer №1

Give this a try

Check out the live demo

Your HTML code

<div ng-app='MyModule'>
    <div ng-controller='DefaultCtrl'>
        <input auto  ng-model="selected">
        selected = {{selected}}
    </div>
</div>

Javascript code

function DefaultCtrl($scope) {

}

angular.module('MyModule', []).directive('auto', function($timeout) {
    var names = ["john", "bill", "charlie", "robert", "alban", "oscar", "marie", "celine", "brad", "drew", "rebecca", "michel", "francis", "jean", "paul", "pierre", "nicolas", "alfred", "gerard", "louis", "albert", "edouard", "benoit", "guillaume", "nicolas", "joseph"];

    return {
        restrict : 'A',
        require : 'ngModel',
        link : function(scope, iElement, iAttrs) {
            iElement.autocomplete({
                source: names,
                select: function() {
                    $timeout(function() {
                      iElement.trigger('input');
                    }, 0);
                }
            });
    }
    };
});

Answer №2

If you are in need of a similar solution using only Angular, the following is an illustration of a pure angular auto-complete feature.

JS:

function DefaultCtrl($scope) {
    $scope.names = ["john", "bill", "charlie", "robert", "alban", "oscar", "marie", "celine", "brad", "drew", "rebecca", "michel", "francis", "jean".];
    $scope.showlist = false;
    $scope.clearList = function(){
        $scope.selected = null;
      $scope.showlist = false;
    }

    $scope.selectedItem = function($event, name){
        $scope.selected = name;
      $scope.showlist = false;
    }
}

angular.module('MyModule', []).directive('autoComplete', function($timeout) {
    return function(scope, iElement, iAttrs) {
            iElement.bind("keypress", function(e){
                    scope.showlist = true;
            })
    };
})

HTML:

<div ng-app='MyModule'>
    <div ng-controller='DefaultCtrl'>
        <input auto-complete ui-items="names" ng-model="selected">
        <button ng-click="clearList()">Clear
        </button>
        <ul ng-show="showlist">
            <li ng-repeat="name in names | filter: selected" ng-click="selectedItem($event, name)">
              {{name}}
            </li>
        </ul>
    </div>
</div>

To see this implementation in action, feel free to check out the fiddle here

Answer №3

Use the following code for autocomplete functionality:

<div>
  <input type="text" placeholder="Search for UserName" class="form-control" ng-keydown="checkKeyDown($event)" ng-keyup="checkKeyUp($event)" ng-model="Filters.UserId" ng-change="search()" />

Your jQuery Code:

//Function to Trigger on ng-change
$scope.search = function () {
    $scope.searchItems = $rootScope.users;

    //Sort Array       
    $scope.searchItems.sort();
   
    //Define Suggestions List
    $scope.suggestions = [];
    
    //Define Selected Suggestion Item
    $scope.selectedIndex = -1;
    $scope.suggestions = [];
    
    var myMaxSuggestionListLength = 0;
    
    for (var i = 0; i < $scope.searchItems.length; i++) {
        var searchItemsSmallLetters = angular.lowercase($scope.searchItems[i].UserID);
        var searchTextSmallLetters = angular.lowercase($scope.Filters.UserId);
        
        if (searchItemsSmallLetters.indexOf(searchTextSmallLetters) !== -1) {
            $scope.suggestions.push(searchItemsSmallLetters);
            myMaxSuggestionListLength += 1;
            
            if (myMaxSuggestionListLength == 10) {
                break;
            }
        }
    }
}

//Keep Track Of Search Text Value During The Selection From The Suggestions List  
$scope.$watch('selectedIndex', function (val) {
    if (val !== -1 && val != undefined) {
        $scope.Filters.UserId = $scope.suggestions[$scope.selectedIndex];
    }
});

//Text Field Events
//Function To Call on ng-keydown
$scope.checkKeyDown = function (event) {
    if (event.keyCode === 40) {//down key, increment selectedIndex
        event.preventDefault();
        
        if ($scope.selectedIndex + 1 !== $scope.suggestions.length) {
            $scope.selectedIndex++;
        }
    } else if (event.keyCode === 38) { //up key, decrement selectedIndex
        event.preventDefault();
        
        if ($scope.selectedIndex - 1 !== -1) {
            $scope.selectedIndex--;
        }
    } else if (event.keyCode === 13) { //enter key, empty suggestions array
        event.preventDefault();
        $scope.suggestions = [];
    }
}

//Function To Call on ng-keyup
$scope.checkKeyUp = function (event) {
    if (event.keyCode !== 8 || event.keyCode !== 46) {//delete or backspace
        if ($scope.Filters.UserId == "") {
            $scope.suggestions = [];
        }
    }
}
//======================================

//List Item Events
//Function To Call on ng-click
$scope.AssignValueAndHide = function (index) {
    $scope.Filters.UserId = $scope.suggestions[index];
    $scope.suggestions = [];
}
//======================================
//End of User Autocomplete Functionality

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

Show a distinct cursor when hovering over text (excluding the element)

When the default cursor hovers over text, it switches to a caret-shaped cursor. This behavior only occurs when hovering over text; if you hover elsewhere inside the element, the specific cursor will not be displayed. For example, I am aiming for a setup s ...

Analyzing string values in Cypress

When attempting to compare two values within a page and make an assertion, my goal is to retrieve the value of one text element and compare it with another value on the same page. While I find this process straightforward in Java/selenium, achieving the ...

JavaScript validation for checkboxes

Here is some code that I am working with: $('#bnp-agree').keyup(function(e){ if(!$(this).is(':checked').val()) e.preventDefault(); }).focusout(function(){ if(!$(this).is(':checked').val()){ $('#bnp-agree-wron ...

Angular's observable function is not providing a complete response

In my Angular component, I have a function that is called from a template. This function returns an Observable of type string, but unfortunately it only returns the `data` variable. How can I modify it to return `dateNew[0] + " de " + data + " de "+ dateNe ...

Having trouble exporting a static HTML file using Next.js

https://i.stack.imgur.com/xQj7q.pngI'm a beginner in the world of React. Recently, I completed a project where I utilized "next build && next export" in my package.json file for static HTML export. By running the npm run build command, an out folder w ...

Execute Code After Function Completion OR DIV Shows Up

I've created a custom Userscript for Facebook that groups similar notifications together. Surprisingly, it works flawlessly when tested with old notifications on a static HTML page. However, there is an issue: The default DIV container for notificati ...

Generate a unique splatter design using Cascading Style Sheets

Imagine a circle link that transforms into a playful animation with a pink shape when you move your mouse over it: I'm torn between different ideas on how to achieve this effect. One approach could be to use individual elements for each drop, utilizi ...

Establish Angular data for all fields in the form

Being a beginner in Angular, I'm struggling with creating a form to update user information. Here's a snippet of my controller: // Fetch organization data from the database dataService.allOrganization().then(function ...

Place the elements for the children prior to the text within

I'm currently using jQuery/JavaScript to insert various elements into an existing <div>. The code is functioning properly, but I would like the text to be added after the initial image. Is there a straightforward way in jQuery to insert the chi ...

Issue encountered: Component returning nothing error in a Next.js/React application

I'm currently working on creating image slider component using Nextjs/React and Emotion. I thought I had everything set up correctly but unfortunately, I keep encountering this common error... Error: ImageSliderContainer(...): Nothing was returned f ...

What steps can be taken to address TypeScript error TS2339: Property 'XXX' is not present on type 'IntrinsicAttributes & ...?

Currently in my typescript/reactjs application, I am attempting to pass a property named 'test' like so in the index.tsx file: ReactDOM.render( <Provider store={getStore()}> <BrowserRouter> <App test={1} /> < ...

Transferring information within React components

Looking for some assistance with the code below. I'm facing an issue where the data is not being submitted along with the form, even though the correct values are displayed in the form. I have included a user query to fetch data from another object an ...

Utilize angularjs daterangepicker to refine and sift through data

I am currently utilizing the ng-bs-daterangepicker plugin by ng-bs-daterangepicker and encountering difficulty in filtering when selecting a start date and end date. Below is a snippet of my code: <input type="daterange" ng-model="dates" ranges="range ...

Utilizing async parallel for executing multiple queries

Hey there, I'm new to Javascript and I've been trying to work with the async.parallel function. I have a specific task where I am fetching data from my database and storing it in an array called "reviewArr." Then, I want to return this array of ...

AngularJS does not hide the Onsen UI modal

I am new to working with angularjs and onsen ui. I have implemented a modal in an ajax request, which is supposed to hide upon successful response. Everything seems to be working fine, except for the fact that when I navigate back to the page, the modal re ...

Creating websites with Single-page applications by assembling HTML and JS fragments at build-time

As I prepare to tackle a large single-page app project, my main focus is on finding a more efficient way to develop it other than cramming everything into one massive file. My priority is ensuring the maintainability and testability of the app, which is wh ...

What could be the reason the forEachRow function is not impacting the second or subsequent pages within the dhtmlx grid?

I'm trying to format the grid rows as they load. My goal is to have the row appear in red with some conditions. It works correctly for the first page, but not for subsequent pages of the grid. Below is my detailed code. If anyone knows why this is hap ...

Ways to display an SVG spinner prior to a substantial UI refresh

I am currently facing an issue with updating 10 apexcharts bar charts simultaneously in a Vue app. When this process occurs, it takes approximately one second to load completely, and during that time, I would like to display an svg spinner. However, the co ...

Is there a way to effortlessly launch a new window with just a single click?

I'm encountering an issue with a function that is supposed to open a new window when a button is clicked. Strangely, on the first click, nothing happens, but on the second click, the window finally opens. Here's my code: Script <script src ...

The process of informing users via email after permission has been granted

Is there a way to notify users via email, similar to how Google Analytics does in their web application, once permissions have been granted? I am currently using this method. Here is an example of my request: var request = gapi.client.analytics.management ...