AngularJS : broadcast event from directive

Sam picture Sam · Apr 24, 2013 · Viewed 63.5k times · Source

I've seen people doing this from wherever in their code:

$rootScope.$broadcast('someEvent', someParameter); 

and then in some controller:

$rootScope.$on('someEvent', function(event, e){ /* implementation here */ });

Now, I'd like to broacast an event from a directive. Is it good practice to broadcast it at rootScope level ? I would like to handle this event in a controller. Can I use $scope, or do I still have to listen on $rootScope ?

Answer

Mark Rajcok picture Mark Rajcok · Apr 24, 2013

In my case, I just want to broadcast an event from a directive to the controller of the view, in which I use the directive. Does it still make sense to use broadcast then?

I would have the directive call a method on the controller, which is specified in the HTML where the directive is used:

For a directive that uses an isolate scope:

<div my-dir ctrl-fn="someCtrlFn(arg1)"></div>

app.directive('myDir', function() {
  return {
    scope: { ctrlFn: '&' },
    link: function(scope, element, attrs) {
       ...
       scope.ctrlFn({arg1: someValue});
    }

For a directive that does not use an isolate scope:

<div my-dir ctrl-fn="someCtrlFn(arg1)"></div>

app.directive('myDir', function($parse) {
  return {
    scope: true,  // or no new scope -- i.e., remove this line
    link: function(scope, element, attrs) {
       var invoker = $parse(attrs.ctrlFn);
       ...
       invoker(scope, {arg1: someValue} );
    }