Angular JS - Automatically focus input and show ty

2019-01-07 11:01发布

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 have a directive that automatically focuses the input field when the button is clicked. How can I show the dropdown automatically so the user can use the down arrow, or click, to quickly choose a user?

I have created a Plunker with the ui-bootstrap JS file editable for tinkering:

http://plnkr.co/edit/Z79LY0OYlwFc3wirjxol?p=preview

This is my full script:

<!doctype html>
<html ng-app="plunker">
  <head>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.js"></script>
    <script src="ui-bootstrap-tpls-0.10.0.js"></script>
  </head>
  <body>

<script>
  angular.module('plunker', ['ui.bootstrap'])
  .directive('focusMe', function($timeout, $parse) {
    return {
        //scope: true,   // optionally create a child scope
        link: function(scope, element, attrs) {
            var model = $parse(attrs.focusMe);
            scope.$watch(model, function(value) {
                if(value === true) { 
                    $timeout(function() {
                        element[0].focus(); 
                    });
                }
            });

        }
    };
});
function TypeaheadCtrl($scope, $http) {

  $scope.selected = undefined;
  $scope.states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Dakota', 'North Carolina', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];
  $scope.opened = false;

  $scope.open = function() {
    $scope.opened = true;
  }
  $scope.close = function() {
    $scope.opened = false;
  }
}

</script>
<div class='container-fluid' ng-controller="TypeaheadCtrl">

    <h4>How can I open the typeahead dropdown automatically when button is pressed?</h4>
    <p>I have a directive that automatically focuses on the field but I can't seem to automatically show the typeahead. Even adding down arrow key click support would be great.

    <br/><br/>

    <button class="btn btn-default" ng-show="!opened" ng-click="open()">Open Input and show typeahead!</button>
    <button class="btn btn-default" ng-show="opened" ng-click="close()">Close Input</button>
    <br/><br/>

    <input type="text"
    focus-me="opened"
    ng-show="opened"
    ng-model="selected" 
    typeahead="state for state in states | filter:$viewValue | limitTo:8" 
    class="form-control">


    <br/>
    <pre ng-show="opened">Model: {{selected | json}}</pre>


</div>
  </body>
</html>

11条回答
神经病院院长
2楼-- · 2019-01-07 11:55

I wanted something like the OP's description and the only solution I found was to come up with a template that combines the dropdown and typeahead directives - maybe the OP or someone else will find it useful:

angular.module('app', ['ui.bootstrap'])
.controller('AppCtrl', function($scope) {
  $scope.model;
  $scope.options = [{label:'Option 1'}, {label:'Option 2'}, {label:'Option 3'}];
  
  $scope.onSelect = function($item, $model, $label) {
    $scope.model = angular.copy($item);
  }
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.12.0/ui-bootstrap-tpls.min.js"></script>

<div ng-app='app' style='padding:10px'>
  <div ng-controller='AppCtrl'>
    <div class='dropdown' dropdown style='width:200px'>
      <!-- This needs UI Bootstrap 0.12 to work -->
      <div class='input-group'>
        <input type='text' class='form-control' ng-model='model.label' typeahead="op.label for op in options | filter:$viewValue | limitTo:8" typeahead-editable='false' />
        <span class='input-group-btn'>
          <button class='btn btn-default dropdown-toggle' dropdown-toggle>
            <span class='caret'></span>
          </button>
        </span>
      </div>
      <ul class="dropdown-menu" role='menu' style='max-height:200px;overflow-y:scroll'>
        <li ng-repeat='op in options'>
          <a href ng-click='onSelect(op)'>{{op.label}}</a>
        </li>
      </ul>
    </div>
  </div>
</div>

Of course, you could simplify it to make the options just an array of strings- I made them objects because that was more like what I needed.

查看更多
淡お忘
3楼-- · 2019-01-07 11:58

Now, as I don't have enough reputation to comment, I must write a new answer to warn people about runTarm's answer above. This is a viable solution, but it runs the risk of running into the following error:

Error: [$rootScope:inprog] $apply already in progress

This seems to be due to ng-focus being a synchronized event (see discussion here). Instead, one can use the ng-click-attribute, and this error doesn't occur.

Also, I've verified that

$element.triggerHandler('input');

works just as good as the jQuery-trigger in runTarm's answer.

查看更多
小情绪 Triste *
4楼-- · 2019-01-07 12:00

I got a working solution by changing some code in ui-bootstrap-tpls-0.10.0.js. So there are no differences in the typeahead html markup.

You can have a look here at http://plnkr.co/edit/LXHDpL?p=preview.

To use this fix, use the ui-bootstrap-tpls-0.10.0.js from the Plunk. To see my changes, open ui-bootstrap-tpls-0.10.0.js from the Plunk and search for 'ahneo'.

 1. //minimal no of characters that needs to be entered before typeahead
    kicks-in
    // ahneo :: before
    //var minSearch = originalScope.$eval(attrs.typeaheadMinLength) || 1;
    // ahneo :: after (changed minimal no of characters to 0 by default)
    var minSearch = originalScope.$eval(attrs.typeaheadMinLength) || 0;
 2. // ahneo :: new (set input value to empty string if it contains " " string value)
    if (inputValue === ' ') {
        inputValue = '';
        modelCtrl.$setViewValue('');
    }  
 3. // ahneo :: before
    //if (inputValue && inputValue.length >= minSearch) {
    // ahneo :: after (add new condition to get matches for min search = 0)
    if (minSearch === 0 || inputValue && inputValue.length >= minSearch) {
 4. // ahneo :: new (bind element to focus event to trigger modelCtrl.$parsers.unshift method)
    element.bind('focus', function (evt) {
        if (modelCtrl.$viewValue === '') {
            modelCtrl.$setViewValue(' ');
        }
    });

Hope this helps

查看更多
相关推荐>>
5楼-- · 2019-01-07 12:00

Seems like built-in support for this feature is coming in an upcoming release in the form of typeahead-min-length attribute supporting value of 0.

It is implemented in this commit in the master branch https://github.com/angular-ui/bootstrap/commit/d859f42cc022a5d8779f1c7b358486bbdd04ed57, but there is no release with this yet and it's not in the 0.14.x branch.

Hopefully a new release will come quickly so that there is no need for these workarounds anymore.

查看更多
祖国的老花朵
6楼-- · 2019-01-07 12:06

As HarishR mentioned in a comment, there is no built-in support for this feature yet.

But I just want to try hacking around and here is the result: http://plnkr.co/edit/Qrnat8yTvISuM1qHHDlA?p=preview

It contains a lot of hacks to make it works:

  1. include jQuery in order to use .trigger(), could be replace with native JS but I'm lazy.
  2. use ng-focus to call .trigger('input') for triggering the typehead popup
  3. use ng-trim="false" to disable input's value auto trimming
  4. a custom empty-typeahead directive that interact with the ngModel's controller for applying the secretEmptyKey logic to bypass typeahead-min-length check:

    .directive('emptyTypeahead', function () {
      return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
          // this parser run before typeahead's parser
          modelCtrl.$parsers.unshift(function (inputValue) {
            var value = (inputValue ? inputValue : secretEmptyKey); // replace empty string with secretEmptyKey to bypass typeahead-min-length check
            modelCtrl.$viewValue = value; // this $viewValue must match the inputValue pass to typehead directive
            return value;
          });
    
          // this parser run after typeahead's parser
          modelCtrl.$parsers.push(function (inputValue) {
            return inputValue === secretEmptyKey ? '' : inputValue; // set the secretEmptyKey back to empty string
          });
        }
      }
    })
    
  5. a custom filter comparator function that always return true (show all results) when one argument is the secretEmptyKey:

    $scope.stateComparator = function (state, viewValue) {
      return viewValue === secretEmptyKey || (''+state).toLowerCase().indexOf((''+viewValue).toLowerCase()) > -1;
    };
    
  6. remove the limitTo filter to show all results

  7. set max-height and overflow css properties to show scrollbar if content is too long

Done!

查看更多
登录 后发表回答