AngularJS : What is the best way to bind to a global event in a directive

后端 未结 5 660
野趣味
野趣味 2021-01-29 17:58

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

5条回答
  •  一个人的身影
    2021-01-29 18:52

    Here's one way you could do it, just store your elements in an array, then in the "global event" you can loop through the elements and do what you need to do.

    angular.module('app').directive('myDirective', function($window){
    
        var elements = [];
    
        $window.on('resize', function(){
           elements.forEach(function(element){
               // In here we have our operations on the element
           });
        });
    
        return {
            link: function(scope, element){
                elements.push(element);
            }
        };
    });
    

提交回复
热议问题