AngularJS : broadcast event from directive
Solution 1:
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} );
}
Solution 2:
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.