1
votes

I am using an angular md-autocomplete input on one of my web forms. I've got it all setup and it is working great.

As expected, whenever I type a new character into the autocomplete input a call to my back-end is made to get the autocomplete data. The problem is I don't want to make a back-end call every time a new character is input. I only want the back-end call to fire if it has been x seconds since the last time a back-end call was made.

Here's the function that gets called when a character is input:

function autocomplete(inputValue) {
    var deferred = $q.defer();

    portalState.apiPost(
        'api/cats/search',
        { 
            SearchType: 'all',
            SearchTerm: inputValue
        },
        function(response) {
            deferred.resolve(response.data);
        },
        function(response) {
            deferred.resolve(null);
        });

    return deferred.promise;
}

That's my working function before I try and put in any throttling logic. The main issue I have when I put in throttling logic is that I don't know what to return that will not cause angular to throw an error, for example:

function autocomplete(inputValue) {
    var isCool = false;

    if(isCool) {
        var deferred = $q.defer();

        portalState.apiPost(
            'api/cats/search',
            { 
                SearchType: 'all',
                SearchTerm: inputValue
            },
            function(response) {
                deferred.resolve(response.data);
            },
            function(response) {
                deferred.resolve(null);
            });

        return deferred.promise;
    }
    else {
        //is there some sort of
        //empty promise I can return
        //so that angular won't
        //throw an error
    }
}

So what can I return if I don't want to make the back-end call? Or is there an easier way to throttle an angular md-autocomplete input?

1
You can set a number of characters before it start searching on your back-endPaulo Galdo Sandoval

1 Answers

3
votes

If you check the documentation on Angular Material, you can set two things.

A number of character to start searching on your back end with md-min-length

Or Also an amount of time in miliseconds with md-delay

Please check here md-autocomplete