Amit Agarwal
Amit Agarwal

Reputation: 61

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.

Upvotes: 3

Views: 2085

Answers (1)

RSquared
RSquared

Reputation: 1188

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

Upvotes: 2

Related Questions