Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use ng-change in angular typeahead search

I want to search user list on key press event. I am using customTemplate.js for showing list, but on first key press result list is not getting displayed.

Here is my code:

<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;
            }
        });
    };
like image 780
Kirti Avatar asked Jan 07 '23 17:01

Kirti


1 Answers

ng-change is actually triggered before the ng-model is updated.

One solution I found was simply to add the typeahead-wait-ms attribute (for a negligible time frame) to your typeahead input element

<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-wait-ms=10
       typeahead-on-select="onSelect($item, $model, $label)" 
       typeahead-template-url="customTemplate.html"  />

this 10ms pause should be enough to allow the ng-model to update before the ng-change event is triggered.

like image 153
sfletche Avatar answered Jan 10 '23 19:01

sfletche