AngularJS:从指令广播事件 [英] AngularJS : broadcast event from directive

查看:330
本文介绍了AngularJS:从指令广播事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过人们从这样的地方在他们的code:

  $ rootScope $广播('someEvent',someParameter)。

,然后在一些控制器:

  $ rootScope在$('someEvent',函数(事件,E){/ *在这里执行* /});

现在,我想从一个指令broacast的事件。它是很好的做法在rootScope水平播出呢?我想在一个控制器来处理此事件。我可以用$范围,或者说我还是要听上$ rootScope?


解决方案

  

在我而言,我只是想即使从指令的观点,我在其中使用指令的控制器广播的。是否还有意义使用广播呢?


我将有指令呼叫的控制器,它是在使用该指令在HTML指定上的方法:

有关使用一个分离范围指令:

 < D​​IV我-DIR CTRL-FN =someCtrlFn(ARG1)>< / DIV>app.directive('MYDIR',函数(){
  返回{
    适用范围:{ctrlFn:'和;' },
    链接:功能(范围,元素,ATTRS){
       ...
       scope.ctrlFn({ARG1:someValue中});
    }

对于不使用分离范围指令:

 < D​​IV我-DIR CTRL-FN =someCtrlFn(ARG1)>< / DIV>app.directive('MYDIR',函数($解析){
  返回{
    适用范围:真,//或没有新的范围 - 即删除此行
    链接:功能(范围,元素,ATTRS){
       VAR调用= $解析(attrs.ctrlFn);
       ...
       调用(范围,{ARG1:someValue中});
    }

I've seen people doing this from wherever in their code:

$rootScope.$broadcast('someEvent', someParameter); 

and then in some controller:

$rootScope.$on('someEvent', function(event, e){ /* implementation here */ });

Now, I'd like to broacast an event from a directive. Is it good practice to broadcast it at rootScope level ? I would like to handle this event in a controller. Can I use $scope, or do I still have to listen on $rootScope ?

解决方案

In my case, I just want to broadcast an even from a directive to the controller of the view, in which I use the directive. Does it still make sense to use broadcast then?

I would have the directive call a method on the controller, which is specified in the HTML where the directive is used:

For a directive that uses an isolate scope:

<div my-dir ctrl-fn="someCtrlFn(arg1)"></div>

app.directive('myDir', function() {
  return {
    scope: { ctrlFn: '&' },
    link: function(scope, element, attrs) {
       ...
       scope.ctrlFn({arg1: someValue});
    }

For a directive that does not use an isolate scope:

<div my-dir ctrl-fn="someCtrlFn(arg1)"></div>

app.directive('myDir', function($parse) {
  return {
    scope: true,  // or no new scope -- i.e., remove this line
    link: function(scope, element, attrs) {
       var invoker = $parse(attrs.ctrlFn);
       ...
       invoker(scope, {arg1: someValue} );
    }

这篇关于AngularJS:从指令广播事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆