Search code examples
angularjsangular-uiangular-bootstrap

How to trigger click on focus?


Take a look:

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

angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('DropdownCtrl', function ($scope, $log) {

  $scope.status = {
    isopen: false
  };

  $scope.toggleDropdown = function($event) {
    $event.preventDefault();
    $event.stopPropagation();
    $scope.status.isopen = !$scope.status.isopen;
  };
});

Html:

 <div ng-controller="DropdownCtrl">
        <!-- Simple dropdown -->
        <div class="btn-group" dropdown keyboard-nav>
            <input id="simple-btn-keyboard-nav" dropdown-toggle>
            <ul class="dropdown-menu" role="menu" aria-labelledby="simple-btn-keyboard-nav">
                <li role="menuitem"><a href="#">Action</a></li>
                <li role="menuitem"><a href="#">Another action</a></li>
                <li role="menuitem"><a href="#">Something else here</a></li>
                <li class="divider"></li>
                <li role="menuitem"><a href="#">Separated link</a></li>
            </ul>
        </div>
    </div>

As you Can see drop-down toggles only on mouse click, but not on focus with tab, or even pressing enter after that.

How can I make it so it can also trigger the dropdown on focus with TAB?


Solution

  • You were not far but your HTML template was missing some elements. Change it to this:

    <div class="btn-group" dropdown keyboard-nav is-open="status.isopen">
      <input id="simple-btn-keyboard-nav" ng-focus="toggleDropdown($event)" dropdown-toggle>
      <ul class="dropdown-menu" role="menu" aria-labelledby="simple-btn-keyboard-nav">
        <li role="menuitem"><a href="#">Action</a></li>
        <li role="menuitem"><a href="#">Another action</a></li>
        <li role="menuitem"><a href="#">Something else here</a></li>
        <li class="divider"></li>
        <li role="menuitem"><a href="#">Separated link</a></li>
      </ul>
    </div>
    

    You were missing the is-open flag. I added an ng-focus event that toggles your dropdown.

    Now you have to find a way to prevent the click and focus events to conflict with each other. I didn't spend time solving this problem because I'm not too about your UI yet.