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 ?
The difference between $broadcast() and $emit() is that the former sends the event from the current controller to all of its child controllers. That means $broadcast() sends an even downwards from parent to child controllers. The $emit() method, on the other hand, does exactly opposite.
Broadcast: We can pass the value from parent to child (i.e parent -> child controller.) Emit: we can pass the value from child to parent (i.e.child ->parent controller.) On: catch the event dispatched by $broadcast or $emit .
The AngularJS $emit method is used to dispatches an event name upwards and travel up to $rootScope. scope listeners. The $emit propagatesevent name upward and travel upwards toward $rootScope. scope listeners and calls all registered listeners along the way.
To register a controller to a module, first you have to create an angularjs module using angular object module method() and create a controller by setting up the initial state of the scope object in JavaScript function. You can register a controller with the module object as shown below.
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} ); }
It's usually a good idea not to use the $rootScope as it's global and you shouldn't pollute it unless you really know what you're doing. I would recommend that you read this article about communication between services, directives and controllers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With