使用 outsideClick 关闭自定义指令弹出窗口

Use outsideClick to close custom directive popover

我有一个弹出窗口作为自定义指令,当单击或悬停图标时打开。单击该图标时,弹出窗口会粘住,如果您再次单击该图标,它将关闭。现在,我想在单击弹出窗口以外的任何其他地方来关闭弹出窗口。下面是我的代码...

我的自定义指令

(function () {
  'use strict';

  angular.module('frontend.core.directives')
    .directive('myPopover', [
      function directive() {
        return {
          restrict: 'E',
          templateUrl: '/frontend/core/directives/my-popover/my-popover.html',
          scope: {
            trigger: '@',
            title:'@'
          },
          transclude: true,
          link: function (scope, elm, attrs) {
            //Need to hide content first
            elm.hide();
            //plugin binder
            $(scope.trigger).popover({
              html: true,
              trigger: 'hover click',
              placement: 'auto',
              content: function () {
                return elm.html();
              },
              title: function () {
                return scope.title;
              }
            });

          }
        };
      }
    ]);
}());

我的HTML

<div>
<i id="touch-details" class="fa fa-info-circle"></i>
<my-popover trigger="#touch-details" my-popover-trigger="outsideClick" title="Details">
    <span>
       Inside of my popover
    </span>
</my-popover>
</div>

请告诉我需要做什么才能在外部单击时关闭弹出窗口。

尝试注入 $document 到你的指令中,并在事件天气中控制点击是在 div 内保持弹出窗口还是在 div 外。所以像这样:

angular.module('frontend.core.directives')
    .directive('myPopover', [
      function directive($document) {

.......

  $document.on('click', function(event){

     event.originalEvent //This holds among other things where the click was made. If click was not made in the div containing the popup, then take an action
});

希望对您有所帮助

有一个名为 popover-trigger 的 属性,您可以在模糊事件上分配 属性 焦点,它可以根据需要工作。此外,通过 ui-bootstrap,您可以轻松地将 bootstrap 的弹出窗口和工具提示与 angularjs 一起使用,如本例所示:

<button popover-placement="top" 
        popover-title="Hello Word!"
        popover-class = "someClass"
        popover-trigger = "focus"
        uib-popover="I appeared on blur!"
        type="button" class="btn btn-default">
        Check
</button> 

其实答案已经创建好了。只需要稍微调整一下以匹配 Angular 语法。所以 '$' 被更改为 'angular.element'。 例如...

$('body').on('click'

等同于

angular.element('body').on('click'

参见link...

http://jsfiddle.net/raving/jpsmegvL/