我有一个指令编译另一个指令并将其附加到具有相同范围的指令体。这与“父”指令的位置不同。
当父指令被销毁时,有没有办法让子指令和作用域也被销毁?我问是因为在检查 DOM 之后,子指令仍然存在。
目前我挂接到 parent 的 $destroy 事件,但很好奇它是否可以自动处理。
jsFiddle: http://jsfiddle.net/FPx4G/1/
当你切换 parent 时, child 会呆在那里,但我想被摧毁。这样做的最佳方法是什么?
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。父元素在一个可以滚动的容器中,因此如果子元素(在一种情况下是一个自定义下拉列表)将被隐藏/截断,如果它比容器大。为了解决这个问题,我改为在文档正文中创建实际的子项并将其相对于父项定位。它还会监听滚动事件以重新定位自己。我有所有的工作并且很好。当我需要删除父项时会发生这种情况...子项仍然存在。
最佳答案
directive("childDirective", function(){
return {
restrict: 'C',
template: '<div >Child Directive</div>',
link: function(scope, element){
scope.$on("$destroy",function() {
element.remove();
});
}
}
});
更新 fiddle :http://jsfiddle.net/C8hs6/
关于html - 在范围销毁上销毁指令/子范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14522426/