Search code examples
javascriptangularjsautocompleteangular-resource

Autocomplete Angularjs from $resource


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();
            }
        });
};

Solution

  • 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.