Search code examples
angular-uiangular-ui-typeahead

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.


Solution

  • 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