Search code examples
javascriptangularjstwitter-bootstrappopoverusing-directives

Use outsideClick to close custom directive popover


I have a popover as a custom directive that opens when an icon is clicked or hovered upon. When the icon is clicked the popover sticks, and will close if you click the icon again. Now I want to close the popover after it's clicked by clicking anywhere else but the popover. Below is my code...

MY CUSTOM DIRECTIVE

(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;
              }
            });

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

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

Please tell me what I need to do to enable closing the popover when clicked outside.


Solution

  • Actually the answer was already created. Just needed to tweak a little to match Angular syntax. So the '$' were changed to 'angular.element'. For example...

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

    is equivalent to

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

    See link...

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