angular.js $ scope。$ broadcast,$ scope。$ emit,$ rootScope。$ broadcast使用什么?

时间:2021-03-27 13:32:19

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.

据我所知,$ broadcast和$ emit之间的区别在于$ broadcast仅在范围树下,并且$ emit上升到范围树。

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.

到目前为止,我一直在为我的活动使用$ rootScope。$ broadcast,这在大多数情况下都是全球性的。这是正确的做事方式吗?如果我有太多rootScope。$ broadcast事件,我应该担心吗?或者这不是问题。

1 个解决方案

#1


3  

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"

通常,您不应该在整个地方注入$ rootScope。它经常成为一个拐杖,你最终会有很多“全局变量”

I'd either build a service that abstracts the $rootScope.broadcast call, or simply use databinding instead:

我要么构建一个抽象$ rootScope.broadcast调用的服务,要么简单地使用数据绑定:

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

      });
    }    
  };
}]);

#1


3  

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"

通常,您不应该在整个地方注入$ rootScope。它经常成为一个拐杖,你最终会有很多“全局变量”

I'd either build a service that abstracts the $rootScope.broadcast call, or simply use databinding instead:

我要么构建一个抽象$ rootScope.broadcast调用的服务,要么简单地使用数据绑定:

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

      });
    }    
  };
}]);