0

I have a problem with an autocomplete and angularjs. I have several ajax request every time i type and this is unusable. I tried to use a timeout without success.. this is code:

$scope.autoCompleteResults = function(){
        $scope.aborter = $q.defer();

        $scope.resource = $resource(URL, {}, {
            getAutocompleteResults: {
                method: "GET",
                timeout: $scope.aborter.promise
            }
        });

        $scope.resource.getAutocompleteResults({}, function (data) {
            if ($scope.searchTxt.length > 1) {

                $scope.autocompleteViewResults = data.data;
                $scope.aborter.resolve();

            } else {
                $scope.autocompleteViewResults = [];
                $scope.search.aborter.reject();
            }
        });
};

1 Answer 1

1

You can try to use the ng-model-options attribute in order to limit the api callings.

Just append ng-model-options="{ debounce: 500 }" to your input, the model will be updated only 0.5 sec after the last change. If the the trigger is a ng-change directive it will limit the amount of query. Don't hestitate to use as well the input directives like ng-minlengthand ng-maxlength

Moreover, you can use a boolean to block the api callings when a query is already in progress.

You could do something like this.

var Resource = $resource(URL, {},{ getAutocompleteResults: { method: "GET" }});

var locked = false;
function getMoreData() {

    if(locked)
        return;
    locked = true;

    Resource.autoCompleteResults()
        .$promise.then(function(data) {
            $scope.autocompleteViewResults = data;
            locked = false;
        });

}

Furthermore I highly recommend you to store your code logic into factories and/or services.

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

4 Comments

have i to declare a timeout in my resource however?
So, i can use the timeout as i have already done before, add your boolean code and even add the model-option?
yes sure, however, in this case you should use the boolean to know when abort the promise instead of simply block the function calling.
well seems working. Amazing!! thank you! Have you other suggestion to make all faster? I'm new in angularjs. You suggested to use ng-minlength, but as you can see i need "count" lenght of text in the input text to fill or empty my data. by the way, this is the input i'm using: <input ng-model="searchTxt" ng-model-options="{ debounce: 500 }" ng-change="autoCompleteResults()" type="text" placeholder="Search..">

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.