I'm building a search directive which I want multiple other directives of my application to be able to listen for changes to the text search.
I am trying to understand the difference between broadcast and emit, and what is best to suit my purposes.
As I understand it, the difference between $broadcast and $emit is that $broadcast goes down the scope tree only, and that $emit goes up the scope tree.
Up to this point I've been using $rootScope.$broadcast for my events, which for the most part have been global in scope. Is this the right way of doing things? Should I be concerned if I have too many rootScope.$broadcast events? Or is that a non-issue.
$broadcast in AngularJS? The $rootScope. $broadcast is used to broadcast a “global” event that can be caught by any listener of that particular scope. The descendant scopes can catch and handle this event by using $scope.
As you can see, the service object uses $rootScope. $emit() to announce interval events and the directive uses $rootScope. $on() to listen for those events.
The difference between $broadcast() and $emit() is that the $broadcast() sends the event from the current controller to all of its child controllers. The $emit() method sends an event from current controller to all of its parent controllers.
In similar way, you can use use the sharedService inside any component & fetch the returing output and used inside your view. That's it. I found this solution as a good alternative of rootScope. You can use this inside your angular 2/4 application.
Generally, you shouldn't inject $rootScope
all over the place. It can often becomes a crutch and you'll end up having a lot of "global variables"
I'd either build a service that abstracts the $rootScope.broadcast
call, or simply use databinding instead:
<my-directive text-search="foo"></my-directive>
with a controller like:
.directive('myDirective', [function() {
return {
link: function($element, $scope, $attrs) {
$scope.$watch($attrs.textSearch, function(newValue, oldValue) {
// Do stuff here...
});
}
};
}]);
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