Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement server-side search box in AngularJS

What is a fast and efficient way to implement the server-side component for an autocomplete feature in an html input box using AngularJS?

I want to implement functionality like we can set a timer task that gets reset after every key stroke, with a .5 second delay. This way if a user types multiple characters fast it doesn't query the index every stroke, only when the user pauses for a second.

Currently, I am using this code-

In Html-

<input class="form-control" ng-model="Search" ng-change="SearchResults(Search)" type="text" />

And My javascript code is-

$scope.SearchResults = function (SearchText) {
        $scope.Request = new Request();
        $scope.Request.Criteria = "[{Key:'SearchText', Value:'" + SearchText + "'}]";
        projectRepository.get($scope.Request.get(), function (data) {
            $scope.Projects = data.Data;
            $scope.Request.set(data);  
        })
    }

Thanks in advance.

like image 343
Amit Agarwal Avatar asked Apr 01 '26 12:04

Amit Agarwal


1 Answers

Before sending off the get request, I would create a timeout which gets cleared each time you type in the input box. Something like this:

var promise;
$scope.SearchResults = function (SearchText) {
    if(promise) $timeout.cancel(promise);

    promise = $timeout(function(){
        // do service call
        alert(SearchText);           
    }, 500);
}

JSFiddle: http://jsfiddle.net/o4ntvvdg/

Note that there should be some logic which cancel old requests every time the user sends off a new request. Otherwise you would need to queue them and figure out which one is the latest one.

EDIT: Fixed wrong description to solution

like image 89
RSquared Avatar answered Apr 03 '26 01:04

RSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!