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.


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

      });
    }    
  };
}]);
链接地址: http://www.djcxy.com/p/18730.html

上一篇: 意外的文档结束(在android.view.MenuInflater.parseMenu)

下一篇: angular.js $ scope。$ broadcast,$ scope。$ emit,$ rootScope。$ broadcast使用什么?