角度切换自定义下拉列表

时间:2017-05-18 14:45:11

标签: javascript angularjs

我有一个自定义下拉选择器。当我点击浏览器上的任何其他位置时,我想切换下拉列表。 toggleModules()正在下拉列表中工作。

数据:modules=["A", "B", "C", "D", "E", "F"]

<div class="col-xl-3 col-lg-3 col-md-3 col-sm-12">
    <div class="vov-filters ov-filter-region">
        <span ng-click="toggleModules($event)"><label>Module</label>
            <b id="caret-glyph" class="glyphicon glyphicon-chevron-down pull-right" area-hidden="true"></b>
        </span>

        <div id="el1" class="overlay bordered" ng-if="showModules">
            <span role="button" ng-click="clearSelectedModules()" class="clear">Clear</span>
                <div class="filter-checkbox" ng-repeat="entry in modules" ng-click="moduleFilter(entry)">
                    <label>
                        <input ng-show="entry.show" type="checkbox" ng-model="entry.show">
                        <span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>
                        {{entry.name}}
                    </label>
                </div>
            </div>

        </div>
    </div>

控制器:切换fn -

  $scope.toggleModules = function(ev) {
      ev.preventDefault();
      ev.stopPropagation();
      $scope.showModules = !$scope.showModules;
      if ($scope.showModules) {
        $scope.overlay = true;
      } else {
        $scope.overlay = false;
      }
    };

相同的控制器:$ document Click Event:

$document.on('click', function(event) {
  <!-- Start Toggle Module filter -->
  $scope.toggleModules(event)
  <!-- End Toggle Module filter -->
  return $document.off('click', event);
});

2 个答案:

答案 0 :(得分:1)

谢谢你们。我找到了一个适合我的解决方案。

$document.on('click', function(event) {
    event.preventDefault();
    event.stopPropagation();
    $scope.$apply(function() {
        $scope.showModules = false;
    });
    $document.off('click', event);
});

答案 1 :(得分:0)

您可以创建一个新的点击指令,可以检查div外的点击,然后执行您想要的任何操作

myApp.directive('clickOff', function($parse, $document) {
var dir = {
    compile: function($element, attr) {
      // Parse the expression to be executed
      // whenever someone clicks _off_ this element.
      var fn = $parse(attr["clickOff"]);
      return function(scope, element, attr) {
        // add a click handler to the element that
        // stops the event propagation.
        element.bind("click", function(event) {
          console.log("stopProp");
          event.stopPropagation();
        });
        angular.element($document[0].body).bind("click",                                                                 function(event) {
            console.log("cancel.");
            scope.$apply(function() {
                fn(scope, {$event:event});
            });
        });
      };
    }
  };
  return dir;
});

Here's a fiddle