How to determine if a directive element is * not * clicked in Angular

I am trying to implement a "deselect" function for several directives like buttons and popovers. That is, I want my functions to run when the user clicks on an element that is not part of my directive template. I am currently using the following JQuery code:

$('body').click(function(evt){
  if($(evt.target).closest($('#directive1')).length == 0 ){
    //deselects first directive
  }

  if($(evt.target).closest($('#directive2')).length == 0 ){
    //deselects second directive
  }

})

      

Is there a better way to do this in angular?

+3


source to share


1 answer


A simple directive that detects a click outside the element (no jQuery):

http://jsbin.com/wimeyoruxo/2/edit

app.directive('onDeselect', [ '$document', function($document) {

  return {
    scope: { onDeselect: '&' },
    link: function(scope, element, attrs) {

      var clickHandler = function(e) {

        // Check if the target is our element or it descendants
        var target = e.target;
        while (target) {
          if (element[0] === target) return;
          target = target.parentElement;
        }

        // trigger the function
        scope.$apply(function() {
          scope.onDeselect({$event:e});
        });
      };

      $document.on('click', clickHandler);

      // clean handler on destroy
      scope.$on('$destroy', function() {
        $document.off('click', clickHandler);
      });
    }
  };
}]);

      



Use it like this:

<div on-deselect="doSomething($event)"></div>

      

+3


source







All Articles