html - 在范围销毁上销毁指令/子范围

标签 html angularjs

我有一个指令编译另一个指令并将其附加到具有相同范围的指令体。这与“父”指令的位置不同。

当父指令被销毁时,有没有办法让子指令和作用域也被销毁?我问是因为在检查 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/

相关文章:

javascript - 更改标题等于的 DIV 文本

javascript - 没有在单选按钮上进行默认检查

html - 图像在放大时移动,但在缩小时保持不变

angularjs - 如何在 AngularJS 中加载 http 请求之前禁用按钮?

javascript - 表单提交后重置 Html 表单并防止用户回来查看提交的数据

HTML电子邮件签名文件在回复中有黑边

javascript - 在 react 中使用 webpack 导入 css

javascript - 如何使用 angularjs 禁用按钮而不更改输入类型复选框的 ng-if 条件?

angularjs - 使用 Yeoman 的 generator-gulp-angular 全栈生成后缺少模块

angularjs - 使用 UI-Router 使用多个 View 的空白页面