【发布时间】:2013-01-25 13:07:30
【问题描述】:
我有一个指令,它编译另一个指令并将它附加到具有相同范围传递的主体上。这与“父”指令的位置不同。
当父指令被销毁时,是否有办法让子指令和作用域也被销毁?我问是因为在检查 DOM 之后,子指令仍然存在。
目前我挂钩了父母 $destroy 事件,但很好奇它是否可以自动处理。
jsFiddle: http://jsfiddle.net/FPx4G/1/
当您切换父级时,孩子会留在那里,但我想被摧毁。最好的方法是什么?
html:
<div ng-app="app">
<div ng-controller="ParentCtrl">
<button data-ng-click="toggleParent()">Toggle Parent</button>
<div data-ng-switch data-on="displayDirective">
<div data-ng-switch-when="true">
<div class="parentDirective">Parent Directive</div>
</div>
</div>
</div>
</div>
javascript:
angular.module('app', [])
.directive("parentDirective", function($compile){
return {
restrict: 'C',
link: function(scope, element){
var secondDirective = angular.element(document.createElement("div"));
secondDirective.addClass("childDirective");
document.body.appendChild(secondDirective[0]);
$compile(secondDirective)(scope);
}
}
})
.directive("childDirective", function(){
return {
restrict: 'C',
template: '<div>Child Directive</div>',
link: function(scope, element){
scope.$on("destroy", function(){
alert(1);
});
}
}
});
function ParentCtrl($scope){
$scope.displayDirective = true;
$scope.toggleParent = function(){
$scope.displayDirective = !$scope.displayDirective;
}
}
通常,我只会在原始指令的模板中包含子元素,以便正确定位。问题实际上归结为处理 z-index。父元素位于可以滚动的容器中,因此如果子元素(在一种情况下为 custom 下拉菜单)比容器大,它将被隐藏/切断。为了解决这个问题,我改为在文档正文中创建实际的孩子并将其相对于父母定位。它还会监听滚动事件以重新定位自己。我有这一切工作,很好。当我需要删除父母时会发生这种情况......孩子仍然在那里。
【问题讨论】:
-
我不知道 Angular 中有这样的功能。我相信您可以为您提供服务。
-
你想做什么?这似乎是一种非常复杂的方法。
-
在底部附近查看我的最新编辑。