dropdown closes on focus

2019-08-04 09:40发布

问题:

I want to trigger dropdown open on focus on input field. But it openes and suddenly closes every time I focus. With button toggle everything is ok. Here is example: http://codepen.io/piernik/pen/ByKRwE

Here is HTML

<div class="input-group">
    <input type="text" class="form-control" ng-focus="show($event)">

    <div class="input-group-addon"><i class="fa fa-fw fa-calendar"></i></div>
</div>
<a class="btn btn-default" ng-click="toggleDropdown($event)">toggle</a>

<div class="dropdown" dropdown is-open="model.open">
    <ul class="dropdown-menu" role="menu">
        Content
    </ul>
</div>

And JS:

$scope.model = {
                open: false
            };
            $scope.toggleDropdown = function ($event) {
                $event.preventDefault();
                $event.stopPropagation();
                $scope.model.open = !$scope.model.open;
            };
            $scope.show = function ($event) {
                $event.preventDefault();
                $event.stopPropagation();
                $scope.model.open = true;
            };
            $scope.hide = function ($event) {
                $event.preventDefault();
                $event.stopPropagation();
                $scope.model.open = false;
            };

回答1:

This is happening because the click event is also triggering in your input, preventing its default behavior.

DEMO

JAVASCRIPT

angular.module('demo', ['ui.bootstrap'])

  .controller('DemoController', function($scope) {

    $scope.open = false;

    $scope.prevent = function($event) {
      $event.stopPropagation();
      $event.preventDefault();
    };

    $scope.focus = function($event) {
      $scope.prevent($event);
      $scope.open = true;
    };

    $scope.toggle = function($event) {
      $scope.prevent($event);
      $scope.open = !$scope.open;
    }

  });

HTML

  <input type="text" check-if-lost-focus ng-click="prevent($event)"  ng-model="name" name="name" ng-focus="focus($event)">
    <div class="btn btn-default" ng-click="toggle($event)">Toggle</div>

    <div class="dropdown" dropdown is-open="open">
      <ul class="dropdown-menu" role="menu">
          Content
      </ul>
  </div>