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

时间:2016-03-18 17:30:36

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

我有一个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>

请告诉我在外面点击时关闭弹出窗口需要做什么。

3 个答案:

答案 0 :(得分:0)

尝试注射 $ document into you directive并控制在事件天气中点击是在持有弹出窗口或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
});

希望有所帮助

答案 1 :(得分:0)

有一个名为popover-trigger的属性,您可以根据需要为blur事件分配属性焦点。此外,使用ui-bootstrap,您可以轻松地使用带有angularjs的bootstrap的popover和工具提示,如下例所示:

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

答案 2 :(得分:0)

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

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

相当于

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

见链接......

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