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

Problem

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.

Problem courtesy of: pedalpete

Solution

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

      });
    }    
  };
}]);
Solution courtesy of: mmattax

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.