gpt4 book ai didi

AngularJS : broadcast event from directive

转载 作者:行者123 更新时间:2023-12-03 05:54:04 24 4
gpt4 key购买 nike

我见过人们在代码中的任何位置执行此操作:

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

然后在某个 Controller 中:

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

现在,我想通过指令广播一个事件。在 rootScope 级别广播它是一个好的做法吗?我想在 Controller 中处理这个事件。我可以使用 $scope 吗,还是仍然需要监听 $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?

我会让指令调用 Controller 上的方法,该方法在使用该指令的 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, element, attrs) {
var invoker = $parse(attrs.ctrlFn);
...
invoker(scope, {arg1: someValue} );
}

关于AngularJS : broadcast event from directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16199212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com