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

Converting a Jquery object into a Javascript object

Can someone help me decipher this piece of code? //... obj.dd.on('click', function(event){ $(this).toggleClass('active'); return false; }); //... $(function() { var dd = new DropDown( $('#dd') ); $(doc ...

Determine the exact scroll position needed to reveal the element when scrolling in reverse

I'm looking for a way to make my div disappear when I scroll down and reappear immediately when I start scrolling back up. Currently, it only works when I reach a certain position instead of taking effect right away. I need assistance in calculating t ...

What is the best way to iterate through values within my JSON document?

Let's say I have a JSON file and I want to iterate through the values in this manner: var myModel = {"id": 0, "date": "2014-10-28", "amount": 1111, "productId": "2", "description": "Cash"}; for (value in myModel) { //element(by.model(key) ...

A guide on applying bold formatting to a specific section of text in React

I have a collection of phrases structured like so: [ { text: "This is a sentence." boldSubstrings: [ { offset: 5, length: 2 } ] } ] My goal is to display each phrase as a line using the following format: ...

Issue with h2 tag within JQuery's read more feature

How can I modify my jQuery code to wrap the middle text in an h2 tag? I am currently using a code snippet from code-tricks. You can find the original code snippets here: $(document).ready(function() { var showChar = 100; var ellipsestext = "..."; ...

Error in Node.js: The res.send method is undefined

I'm having some issues with my first attempt at creating a simple Counter Strike API bot using nodeJS. The problem lies with the res.send function, as I keep getting an error message saying "res.send is not a function" every time I try to use it. Movi ...

Particles are not appearing when using the Three.js shader material

Hey there, I've been working on a simple scene with a grid of particles in the shape of a cube. Check it out here: https://codepen.io/sungaila/pen/qqVXKM The issue I'm facing is that when using a ShaderMaterial, the particles don't seem to ...

Troubleshooting: The issue with json_encode in Ajax calls

I am facing an issue with my ajax call and the json response. The console is indicating that my php file is not returning a json format, but I am unable to pinpoint the exact reason behind it. Below is my ajax function: function showEspece(espece, categori ...

Are tabs best displayed as an overlay?

I've been searching high and low for a tutorial on how to create an overlay with tabs similar to the Google Chrome webstore. If anyone knows of a tutorial or a combination of tutorials that can help me achieve this, please let me know! Link Any guida ...

Observables do not provide any results when used in a pipe with an image src

I recently created a custom pipe for the image src in my application: It is applied to selectors like this: <img [src]="myobject?.URL | secure" /> Here's the code snippet for the pipe: import { Pipe, PipeTransform } from '@angular/c ...

Tips for displaying res.locals information in the console for debugging purposes using ExpressJS and Nodejs

Currently, I am delving into the world of Node.js and ExpressJS as a novice in this realm. My primary requirement is to log the entire or partial content of res.locals in my console for debugging purposes. Here's what I've attempted: var foo_ro ...

Utilizing logic classes in conjunction with styled components

I am seeking a way to utilize this logic in order to assign the appropriate class to an element: <ul onClick={handleClick} className={click ? 'dropdown-menu clicked' : 'dropdown-menu'}> However, as I am employing styled component ...

Retrieve the full directory path that has been chosen in an HTML form

I am facing a similar issue in my web application where I am using PHP, HTML, and JavaScript. What I want is to be able to select a folder and obtain the full path of that folder for backing up data. For example, when a user enters backup.php, they should ...

Struggling with integrating Bootstrap 4 Modals in Angular 2 environment

I attempted to incorporate a modal from into my navbar, but nothing happens when I click on it. <div class="pos-f-t fixed-top header"> <nav class="navbar navbar-inverse bg-inverse navbar-toggleable-md"> <button class="navbar- ...

Creating a webpage with a feature that allows users to click a button and instantly change the background to a

Here is the code I have for generating random colors: const colors = ["green", "red", "rgba(133,122,200)", "#f15025"]; const btn = document.getElementById('btn'); const color = document.querySelector('.color'); btn.addEventListener(&a ...

Is there a way to deactivate all dot inputs on number type input in vue.js 2?

Here is an example of my HTML code: <div id="app"> <input type="number" v-model="quantity"/> </div> This is how my Vue component looks: new Vue({ el: '#app', data: { quantity: '' }, watch: { quanti ...

Can CSS be used to separate elements within a div from the overall page styles, similar to how an iFrame functions?

Is there a way to isolate elements within a div, similar to how it would behave in an iFrame? I am facing issues with the global SharePoint styles affecting my app inside SharePoint. I want to completely disable these global styles so that my app only use ...

Conceal additional recipients in the "to" address field when sending emails with Node.js using Nodemailer

I am currently working on a project called EmailSender using node.js, and I have found that the nodemailer package is incredibly helpful. However, when sending emails to multiple contacts, all recipients are able to see each other's email addresses i ...

What is the most effective way to remove or modify an element in an array when a button is clicked?

I've hit a roadblock because I'm uncertain about how to access and remove elements stored within an array, especially if the user wants to delete from the middle. In this scenario, using pop won't suffice as it removes from the end without c ...

Creating an Angular application with the help of Express generator

I recently set up a project using express generator and installed bower to incorporate bootstrap and angular. My focus is on utilizing express for REST web services and setting up angular routes. While I can access my index page, there seems to be an issue ...