Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Mousedown Event in Angularjs

I know how to detect mousedown event on a directive that is clicked. However my directive also needs to become unforcused or deselected when mouse is down outside of my directive/ element. How can I do this?

like image 887
Dr.Knowitall Avatar asked May 16 '14 04:05

Dr.Knowitall


1 Answers

Create a link function in the directive which binds a mousedown event handler on the document. Then, bind another mousedown event on the directive element itself. The latter handler should also call event.stopPropagation() to prevent the event from bubbling all of the way up to the document level:

link: function(scope, elem, attrs){
  angular.element(document).bind('mousedown', function(){
    console.log('clicked on document');
  });

  elem.bind('mousedown', function(e){
    e.stopPropagation();
    console.log('clicked on directive');
  });
}

Working Plunker

like image 152
Marc Kline Avatar answered Nov 20 '22 21:11

Marc Kline