Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.js $scope.$broadcast, $scope.$emit, $rootScope.$broadcast what to use?

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.

like image 696
pedalpete Avatar asked Jan 21 '14 00:01

pedalpete


People also ask

What is rootScope broadcast in AngularJS?

$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.

What does rootScope emit do?

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.

What is the difference between emit and broadcast in AngularJS?

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.

What is alternative of rootScope in Angular?

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.


1 Answers

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...

      });
    }    
  };
}]);
like image 168
mmattax Avatar answered Oct 11 '22 15:10

mmattax