Angular JS - Automatically focus input and show typeahead dropdown - ui.bootstrap.typeahead

后端 未结 11 1543
孤街浪徒
孤街浪徒 2020-11-30 03:07

I am using Angular JS - ui.bootstrap.typeahead:

I would like to click a button and focus an input field and automatically show the typeahead suggestion dropdown. I h

11条回答
  •  醉话见心
    2020-11-30 03:58

    Updated:

    I added the directive to github for easy updates and access. You can now install it as a dependency through bower.

    Original post:

    I came up with a pretty clean hack that does not require any changes to ui-bootstrap-tpls. The Idea is to use $setViewValue() to trigger the popup with a combination of a special filter comparator function.

    In order to bypass the minLength check, $setViewValue() has to be set to a value longer than 1 so i'm using one space string. The role of the comparator function is to treat one space as a match to all items so they'll all show up when clicking on an empty input.

    I created a simple directive:

    angular.module('app')
    .directive('typeaheadFocus', function () {
      return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModel) {
    
          //trigger the popup on 'click' because 'focus'
          //is also triggered after the item selection
          element.bind('click', function () {
    
            var viewValue = ngModel.$viewValue;
    
            //restore to null value so that the typeahead can detect a change
            if (ngModel.$viewValue == ' ') {
              ngModel.$setViewValue(null);
            }
    
            //force trigger the popup
            ngModel.$setViewValue(' ');
    
            //set the actual value in case there was already a value in the input
            ngModel.$setViewValue(viewValue || ' ');
          });
    
          //compare function that treats the empty space as a match
          scope.emptyOrMatch = function (actual, expected) {
            if (expected == ' ') {
              return true;
            }
            return actual.indexOf(expected) > -1;
          };
        }
      };
    });
    

    Usage:

    
    

提交回复
热议问题