我有一个指令,编译另一个指令并将其附加到具有相同范围的主体.这与"父"指令的位置不同.
当父指令被销毁时,有一些方法可以让子指令和范围也被销毁吗?我问,因为在检查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>
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
通常,我只是在原始指令的模板中有子元素,以便正确定位.问题实际上归结为处理z-index.父元素位于可以滚动的容器中,因此如果子容器大于容器,则子容器(在一种情况下是自定义下拉列表)将被隐藏/切断.为了解决这个问题,我改为在文档正文中创建实际的子对象并将其相对于父对象进行定位.它还会监听滚动事件以重新定位自己.我有所有工作,并且很好.当我需要删除父母时,会发生什么......孩子仍在那里.
Ash*_*ish 16
directive("childDirective", function(){
return {
restrict: 'C',
template: '<div >Child Directive</div>',
link: function(scope, element){
scope.$on("$destroy",function() {
element.remove();
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
更新小提琴:http://jsfiddle.net/C8hs6/