我看到人们在他们的代码中的任何地方这样做:
$rootScope.$broadcast('someEvent',someParameter);
然后在一些控制器中:
$rootScope.$on('someEvent',function(event,e){ /* implementation here */ });
现在,我想从一个指令来炫耀一个事件。是否是在rootScope级别广播它的好习惯?我想在控制器中处理这个事件。我可以使用$ scope,还是我还要在$ 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?
我将有指令在控制器上调用一个方法,这是在使用指令的HTML中指定的:
对于使用隔离范围的指令:
<div my-dir ctrl-fn="someCtrlFn(arg1)"></div> app.directive('myDir',function() { return { scope: { ctrlFn: '&' },link: function(scope,element,attrs) { ... scope.ctrlFn({arg1: someValue}); }
对于不使用隔离范围的指令:
<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,attrs) { var invoker = $parse(attrs.ctrlFn); ... invoker(scope,{arg1: someValue} ); }