tjf*_*dfs 3 angularjs angularjs-directive
为什么我使用的scope.$parent().$emit()不是scope.$emit()指令使用时scope:true,还有一个指令使用scope:true,并且它们放在同一个DOM节点上.
然后scope.$emit()也将事件发送到另一个指令,并且可以像父范围一样捕获.但scope.$parent().$emit()只会向父母发出事件.使用scope.$parent().$emit()好吗?
似乎其他指令是否可以捕获事件似乎并不重要,但我不确定这一点.因此,在某些情况下,可能只发送给父母.
这里有一个例子普拉克
"第二指令"事件只能被MainCtrl捕获.但是"第二指令二"可以被MainCtrl和第一个指令捕获.
以下是相关问题:如何在AngularJS中停止$ broadcast事件?
您可以使用
$rootScope.$broadcast('second-directive-two', 'from second');
Run Code Online (Sandbox Code Playgroud)
代替
$scope.$parent().$emit('second-directive-two', 'from second');
Run Code Online (Sandbox Code Playgroud)
并取消控制器中的事件处理
$scope.$on('second-directive-two',function(event,args){
event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
first如果事件已被阻止,则不要在指令中处理事件'second-directive-two'
$scope.$on('second-directive-two',function(event,args){
if (!event.defaultPrevented) {
// do useful job
}
});
Run Code Online (Sandbox Code Playgroud)
这是插件
更新:
为什么不是好的做法?
在这种情况下,您将绑定到DOM层次结构.想象一下,你必须将指令移动First到partial并通过它包含它ng-include.范围层次结构已更改.$scope.$parent().$emit()从那时起不起作用.你花时间来解决这个问题.
通常$scope.$parent().$emit()生成潜在的问题代码
| 归档时间: |
|
| 查看次数: |
5073 次 |
| 最近记录: |