Discovering the power of ng-change in an Angular typeahead search functionality

I am facing an issue with displaying the result list when searching for users on key press using customTemplate.js. The list is not showing up after the first key press. Below is the code I am using:

<input type="text" placeholder="Search people here..." ng-change="getMatchedUser();"  ng-model="selected" data-typeahead="user as user.name for user in searchMembers | filter:$viewValue" typeahead-on-select="onSelect($item, $model, $label)" typeahead-template-url="customTemplate.html"  /> 

<script type="text/ng-template" id="customTemplate.html">
                <a style="cursor: pointer;">
                    <div class="search-div">
                        <span style="float: left;"><img ng-src="<?php echo base_url().UPLOAD_PROFILE ?>{{match.model.imageUrl}}" width="30" class="img-circle"></span>
                        <div class="search-name">
                            <span>{{match.model.name}}</span><br/>
                            <span ng-if="match.model.skillName.length">
                                <i class="skill">{{match.model.skillName}}</i>
                            </span>
                        </div>
                    </div>
                    <div style="padding-bottom:42px;" ng-if="match.model.length == 5">
                        <a href="<?php echo base_url(); ?>#/searchResult" style="float: left; padding: 18px 1px 5px 8px; color: black;"> 
                            Show More Results
                        </a>    
                    </div>
                </a>
</script> 

$scope.getMatchedUser = function(){
        $scope.searchValue = $scope.selected;
        $http({
            method : "POST",
            url : BASE_URL + 'getMatchedUser',
            data : $.param({"typeValue": $scope.selected}),
            headers : { 'Content-Type' : 'application/x-www-form-urlencoded'}
        }).success(function(data){ 
            if(data.status == "success"){
                $scope.searchMembers = data.searchMembers;
            }
        });
    };

Answer №1

ng-change function gets executed before the ng-model is actually updated.

One workaround that I discovered was to include the typeahead-wait-ms attribute (for a brief duration) in the typeahead input element.

<input type="text" 
       placeholder="Find people here..." 
       ng-change="getMatchedUser();"  
       ng-model="selected" 
       data-typeahead="user as user.name for user in searchMembers | filter:$viewValue" 
       typeahead-wait-ms=10
       typeahead-on-select="onSelect($item, $model, $label)" 
       typeahead-template-url="customTemplate.html"  />

This short 10ms delay allows enough time for the ng-model to update before triggering the ng-change event.

Answer №2

It is recommended to utilize the search feature directly instead of relying on ng-change.

<input type="text" 
       placeholder="Find people here..." 
       ng-model="selected" 
       data-typeahead="user as user.name for user in getMatchedUser($viewValue) | filter:$viewValue" 
       typeahead-wait-ms=10
       typeahead-on-select="onSelect($item, $model, $label)" 
       typeahead-template-url="customTemplate.html"  />

Make sure to update your search function by adding a parameter:

$scope.getMatchedUser = function(query){

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

Unlock the potential of JavaScript by accessing the local variable values in different functions

I've been struggling for days to find a solution to this issue... https://i.stack.imgur.com/KDN7T.jpg https://i.stack.imgur.com/tOfCl.jpg The image above illustrates the challenge I'm facing - trying to apply data values from elsewhere to the ...

The UI in an angular directive is not getting refreshed due to issues with the

Check out this fiddle http://jsfiddle.net/3jos4pLb/ I have a problem where my directive communicates with the parent controller scope by setting the finalValue. However, when the window is resized, the scope.finalValue updates in the console but the UI d ...

Attempting to retrieve AJAX response in JavaScript by utilizing an OOP object

Here is the code snippet I am working with: function CreateDiv(D) { D.body = function () { var d = $.ajax({ type: "GET", url: "Default.aspx", data: 'Ext ...

I'm trying to create a transparent v-card, but for some reason it's not turning out the way I want

How can I make the v-card transparent while keeping its content opaque using CSS? card.vue <v-card class="cardColor"> <v-card-text> TEXT </v-card-text> <v-card-actions> <v-btn color="prima ...

Can a JavaScript or jQuery function be triggered on input change to perform a PHP call to check a database?

Is it possible to implement live form validation without a page reload? I am looking to add a function like the one below: <input onchange="validate();"></input> function validate() { // PHP here to check input value against table value o ...

Using React js to transform objects into arrays for useState

Hey there! I'm currently working on a webshop demo project for my portfolio. I've encountered an issue while trying to fetch data from commerce.js. The data is in the form of objects, which are causing problems when I try to map them. I've a ...

Creating responsive tabs that transition into a drop-down menu for mobile devices is a useful feature for

I am looking to create a responsive tab design that drops down like the example shown below: Desktop/Large Screen View https://i.stack.imgur.com/hiCYz.png Mobile View https://i.stack.imgur.com/gRxLv.png I have written some code for this, but I am unsure ...

Upon clicking the IconButton within the ImageListItemBar, reveal the image within a Material-UI Dialog

import * as React from 'react'; import Box from '@mui/material/Box'; import ImageList from '@mui/material/ImageList'; import ImageListItem from '@mui/material/ImageListItem'; import ImageListItemBar from '@mui/m ...

"Trouble with server communication: data array not being passed to hbs

In my GET route, I have the following: app.get(("/employee/:id"), (req, res) => { data.getEmployeeByNum(req.params.id).then((data) => { res.render("employee", {employee: data}); }).catch(function(reason) { res.render("employe ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

Redux: The action was effectively triggered, but the state remained unformed

I'm currently working on a project to familiarize myself with Redux. I am using the Redux DevTools to monitor my two states: lists and todos. However, I am running into an issue where only todos are being displayed, despite trying various troubleshoot ...

Looking for a fully customizable event and booking calendar?

Currently, I am searching for a unique event and booking calendar that provides the ability to customize each cell or day with our desired content. While most calendars only allow for inputting events as text, we require a solution that enables us to add ...

Ways to conceal a grid item in Material UI framework

My goal is to hide a specific grid item for a product and smoothly slide the others in its place. Currently, I am using the display:none property but it hides the item instantly. I have already filtered the products and now I want to animate the hiding of ...

Is there a way to resolve the MongoDB Database-Differ Error?

I am currently working on creating an API and have set up a brand new Project, cluster, and Collection for it. However, when I attempt to use mongoose.save() to add data to my database, I keep receiving an error message. "message": { " ...

invoking a function at a designated interval

I am currently working on a mobile application built with Ionic and TypeScript. My goal is to continuously update the user's location every 10 minutes. My approach involves calling a function at regular intervals, like this: function updateUserLocat ...

The CSS class is not properly implemented in the React component

I value your time and assistance. I have spent many hours trying to solve this issue but seem unable to reach a resolution. Here is the React component in question: import styles from './style.scss'; class ButtonComponent extends React.Compone ...

It seems that BeautifulSoup and Selenium are unable to locate the div or text elements on the website

I have been attempting to utilize BeautifulSoup or Selenium in order to retrieve the Head to Head text or its corresponding div element on betexplorer (link provided below), but my efforts have unfortunately proved to be unsuccessful. Despite being able to ...

Issue with pagination and filtering in Smart-table.js

Presently, my focus is on developing functionality for Smart-table.js, which requires the following features: Retrieve JSON data from a web service Create a table with pagination and filtering capabilities Implement filters for individual columns or globa ...

Tips for layering one div on top of another div

I'm looking for guidance on how to position my button divs over my Trapezoids in an overlay fashion. Currently, I have set up an array to store the colors and utilizing the map function to match each button with its corresponding color type. When a ...

What is the best way to fetch information from an API using Angular5 with Material2 components?

Here are the 'table.component.html' and 'table.component.ts' files where I am pulling data from an API to display in a table. Below is the object received from the API: [ {position: 1, name: 'Hydrogen', weight: 1.0079, sym ...