【问题标题】:destroy directive/child scope on scope destroy范围销毁上的销毁指令/子范围
【发布时间】: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 中有这样的功能。我相信您可以为您提供服务。
  • 你想做什么?这似乎是一种非常复杂的方法。
  • 在底部附近查看我的最新编辑。

标签: html angularjs


【解决方案1】:
directive("childDirective", function(){
    return {
        restrict: 'C',              
        template: '<div >Child Directive</div>',                
        link: function(scope, element){                  
            scope.$on("$destroy",function() {
                element.remove();
            }); 
        }
    }
});

更新小提琴:http://jsfiddle.net/C8hs6/

【讨论】:

  • 我希望不必听范围销毁事件。如果这是唯一的方法,那就这样吧。
  • 如果它实际上是在 DOM 关系下的子元素,那么你的角度会清理它......但你的场景在这里完全不同,所以这是处理它的技巧。
  • 仅供参考,该元素已经是一个 Angular 包装元素,所以这也可以:element.remove()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 2017-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-21
相关资源
最近更新 更多