Guillaume Morin
Guillaume Morin

Reputation: 4010

How to cancel typeahead-wait-ms on key press

Using an angular-ui typeahead with a wait specified

<input type="text" 
  ng-model="selected" 
  uib-typeahead="state for state in states | filter:$viewValue | limitTo:8" 
  typeahead-focus-first="false"
  typeahead-wait-ms="1000"
  class="form-control">

I would like to cancel the wait and not show typeaheads when ENTER is pressed before the wait time is reached.

Here is a plunker to play: https://plnkr.co/edit/QkYumhmcDsXexHSLALsf?p=preview

So for example, if I enter "a" and then press ENTER before 1000ms is ellapsed, the typeaheads menu should not be shown.

Upvotes: 3

Views: 2105

Answers (2)

Guillaume Morin
Guillaume Morin

Reputation: 4010

Thanks to oFace blur idea, I came up with this directive.

.directive('typeaheadCancelEnter', function () {
        return {
            restrict: 'A',
            link: function ($scope, elem, attrs) {

                elem.bind('keyup', function ($event) {
                    var element = $event.target;
                    var code = $event.keyCode || $event.which;
                    if (code == 13) { //Enter keycode
                      element.blur();    
                    }

                });

            }
        };
    })

https://plnkr.co/edit/vodZHT14zZjdcTEKVKq9?p=preview

Upvotes: 2

oFace
oFace

Reputation: 216

fast fix - not the angular way i fear, but what the heck:

in HTML:

  1. give your input field an id - e.g.: search_input
  2. add a ng-enter="blurme()"

in your TypeaheadCtrl: add a function

$scope.blurme = function() {
    // blur input field to cancel autosuggest after typeahead-wait-ms
    var search_input = document.getElementById ('search-input');
    search_input.blur ();
}

Upvotes: 1

Related Questions