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.
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.
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.
Let's illustrate both options:
Option 1:
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);
             });
        }
    };
});
Option 2:
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);
});
Both approaches are working fine but I feel that option two is not really 'Angular-ish'.
Any ideas?
 
     
     
     
     
     
    