3

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

but when i am deleting or press backspace fastly then show the complete list at time(display for less then 0.2 sec) and then again display the particular text result.
Sorry I have mistaken.. Your solution is working like a charm... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.