6

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?

0

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

will this automatically $apply() as well?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.