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

后端 未结 5 756
野趣味
野趣味 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:40

    In my opinion I would go with method #1 and a little tweak of using the $window service.

    angular.module('app').directive('myDirective', function($window){
    
         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.
                 anguar.element($window).bind('resize', function(){
                      doSomethingFancy(element);
                 });
            }
        };
    });
    

    #2 In reference to this approach and a slight change in thinking here - you could put this event listener somewhere higher up in say app.run - and here when the event happens you can broadcast another event which the directive picks up and does something fancy when that event takes place.

    EDIT: The more I think about this method the more I actually start to like it over the first one... Great robust way to listen to the window resize event - maybe in the future something else needs to "know" this info as well and unless you do something like this you are forced to setup - yet again - another event listener to the window.resize event.

    app.run

    app.run(function($window, $rootScope) {
      angular.element($window).bind('resize', function(){
         $rootScope.$broadcast('window-resize');
      });
    }
    

    Directive angular.module('app').directive('myDirective', function($rootScope){

         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.
                 $rootScope.$on('window-resize', function(){
                      doSomethingFancy(element);
                 });
            }
        };
    });
    

    Finally An awesome source of how to do stuff is to follow the angular-ui guys for example the ui-bootstrap. I have learned a bunch of how to stuff from these guys for example the joys of learning to unit test in angular. They provide a great clean codebase to checkout.

提交回复
热议问题