下拉关闭焦点

时间:2014-12-12 12:16:16

标签: angularjs drop-down-menu angular-ui

我想在关注输入字段时触发打开下拉列表。 但每当我专注时,它就会打开并突然关闭。 使用按钮切换一切都很好。 这是一个例子: http://codepen.io/piernik/pen/ByKRwE

这是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>

和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 个答案:

答案 0 :(得分:2)

这种情况正在发生,因为click事件也会在您的输入中触发,从而阻止其默认行为。

<强> 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>