AngularJS:来自指令的广播事件 [英] AngularJS : broadcast event from directive
问题描述
我见过有人在他们的代码中的任何地方这样做:
I've seen people doing this from wherever in their code:
$rootScope.$broadcast('someEvent', someParameter);
然后在一些控制器中:
$rootScope.$on('someEvent', function(event, e){ /* implementation here */ });
现在,我想从指令广播一个事件.在 rootScope 级别广播它是一种好习惯吗?我想在控制器中处理这个事件.我可以使用 $scope 吗,还是我仍然需要监听 $rootScope ?
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 event from a directive to the controller of the view, in which I use the directive. Does it still make sense to use broadcast then?
我希望指令调用控制器上的方法,该方法在使用指令的 HTML 中指定:
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屋!