最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Binding an event to $(document) inside an angular directive - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Jun 23, 2014 at 10:22 Amir PopovichAmir Popovich 29.8k9 gold badges57 silver badges101 bronze badges 6
  • Could you please provide jsifddle/plunker? – Miraage Commented Jun 23, 2014 at 10:24
  • Actually you write directives when you want to play with /manipulate DOM. So I guess attaching above event handler in your directive is the correct way or rather Angular way of doing such things – Shailesh Vaishampayan Commented Jun 23, 2014 at 10:26
  • Can you show how did you do it and what was the error? – Chandermani Commented Jun 23, 2014 at 10:46
  • You can inject $window which has onclick functions. – Jorg Commented Jun 23, 2014 at 10:53
  • I didn't have any problems. I was looking for the best practice solution as Yuriy Rozhovetskiy gave. – Amir Popovich Commented Jun 23, 2014 at 11:11
 |  Show 1 more comment

1 Answer 1

Reset to default 18

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

发布评论

评论列表(0)

  1. 暂无评论