【问题标题】:Use outsideClick to close custom directive popover使用 outsideClick 关闭自定义指令弹出框
【发布时间】:2016-07-05 13:59:37
【问题描述】:

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

我的自定义指令

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

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

【问题讨论】:

  • 如果您的弹出框后面有某种覆盖,您可以随时检查该覆盖是否已被点击。类似:overlay.on('click', function() {myPopover.close();}); 在你的指令中

标签: javascript angularjs twitter-bootstrap popover using-directives


【解决方案1】:

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

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

等价于

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

查看链接...

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

【讨论】:

    【解决方案2】:

    有一个名为 popover-trigger 的属性,您可以在 blur 事件上分配属性焦点,它可以根据需要工作。此外,通过 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> 
    

    【讨论】:

      【解决方案3】:

      尝试注入 $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
      });
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-24
        • 2020-09-20
        • 2021-08-29
        • 1970-01-01
        • 2017-03-30
        • 2015-04-17
        相关资源
        最近更新 更多