Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding an event to $(document) inside an angular directive

I have a directive which implements kind of a select box.
Now when the select box is open and I click somewhere outside of it(anywhere else in the document) I need it to collapse.

This JQuery code works inside my directive, but I want to do it "the angular way":

  $(document).bind('click', function (e) {
       var $clicked = e.target;
       if (!$clicked.parents().hasClass("myClass")) {
            scope.colapse();
       }
  });

I tried doing thing with injecting the $document service into my directive but didn't succeed.

like image 807
Amir Popovich Avatar asked Jun 23 '14 10:06

Amir Popovich


1 Answers

I believe, the most true Angular way is to use angular.element instead of jQuery and accessing window.document via the $document service:

(function() {

  angular.module('myApp').directive('myDocumentClick', 
    ['$window', '$document', '$log',
    function($window, $document, $log) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          $document.bind('click', function(event) {
            $log.info(event);
            if (angular.element(event.target).hasClass('myClass')) {
              $window.alert('Foo!');
            }
          })
        }
      };
    }
  ]);

})();

Plunker link

like image 200
Yuriy Rozhovetskiy Avatar answered Oct 22 '22 21:10

Yuriy Rozhovetskiy