title: AngularJS : What is the best way to bind to a global event in a directive
body: <p>Imagine the situation in AngularJS where you want to create a directive that needs to respond to a global event. In this case, let's say, the window resize event.</p>
  
  <p>What is the best approach for this? The way I see it, we have two options:
  1. Let every directive bind to the event and do it's magic on the current element
  2. Create a global event listener that does a DOM selector to get each element on which the logic should be applied.</p>
  
  <p>Option 1 has the advantage that you already have access to the element on which you want to do some operations. But...options 2 has the advantage that you do not have to bind multiple times (for each directive) on the same event which can be a performance benefit.</p>
  
  <p>Let's illustrate both options:</p>
  
  <p><strong>Option 1:</strong></p>
  
  <pre><code>angular.module('app').directive('myDirective', function(){
  
       function doSomethingFancy(el){
           // In here we have our operations on the element
      }
  
      return {
          link: function(scope, element){
               // Bind to the window resize event for each directive instance.
               angular.element(window).on('resize', function(){
                    doSomethingFancy(element);
               });
          }
      };
  });
  </code></pre>
  
  <p><strong>Option 2:</strong></p>
  
  <pre><code>angular.module('app').directive('myDirective', function(){
  
      function doSomethingFancy(){
           var elements = document.querySelectorAll('[my-directive]');
           angular.forEach(elements, function(el){
               // In here we have our operations on the element
           });
      }
  
      return {
          link: function(scope, element){
               // Maybe we have to do something in here, maybe not.
          }
      };
  
      // Bind to the window resize event only once.
      angular.element(window).on('resize', doSomethingFancy);
  });
  </code></pre>
  
  <p>Both approaches are working fine but I feel that option two is not really 'Angular-ish'. </p>
  
  <p>Any ideas?</p>