Angular-如何从DOM中删除我使用$compile的元素

Angular - How can I remove from the DOM an element I have used $compile on?

本文关键字:compile 元素 删除 DOM Angular-      更新时间:2023-09-26

我需要的是两个ng视图的功能。因为我不能,我想更改某个内容的innerHTML并编译它。我的问题是,当我再次更改内容时,我可以编译,但angular是否会自行删除绑定,或者我是否必须手动执行,如果是,如何执行?

编辑:解释

我想制作一个模态,我可以更改它的内容并将其绑定到不同的范围(因此使用$compile(。但我不想破坏整个模态,只是它的一些内容,然后换成另一个。我主要怀疑的是,删除一些已编译的HTML是否会导致内存泄漏。

已解决

对于这个问题,我创建了一个新的子作用域(使用$new(,并在更改内容时将其销毁。感谢一切

要手动删除元素,请执行element.remove()。听起来您还想破坏已编译元素的作用域,这样您也可以通过执行scope.$destroy();$scope.$destroy();来实现这一点,具体取决于您是否在指令中。

http://docs.angularjs.org/api/ng.$rootScope.Scope#$destroy

感谢您的良好解决方案。我刚刚发布了一些实现代码

.directive('modal', function($templateCache, $compile) {
    return function(scope, element, attrs) {
        var currentModalId = attrs.modalId;
        var templateHtml = $templateCache.get(attrs.template);
        var modalScope, modalElement;
        scope.$on('modal:open', function(event, modalId) {
            if(modalId == null || currentModalId === modalId) {
                openModal();
            }
        });
        scope.$on('modal:close', function(event, modalId) {
            if(modalId == null || currentModalId === modalId) {
                closeModal();
            }
        });
        function openModal() {
            // always use raw template to prevent ng-repeat directive change previous layout
            modalElement = $(templateHtml);
            // create new inherited scope every time open modal
            modalScope = scope.$new(false);
            // link template to new inherited scope of modal
            $compile(modalElement)(modalScope);
            modalElement.on('hidden.bs.modal', function() {
                if(modalScope != null) {
                    // destroy scope of modal every time close modal
                    modalScope.$destroy();
                }
                modalElement.remove();
            });
            modalElement.modal({
                show: true,
                backdrop: 'static'
            });
        }
        function closeModal() {
            if(modalElement != null) {
                modalElement.modal('hide');
            }
        }
    };
});

这个问题的解决方案是创建一个新的子作用域。由于作用域继承,所有具有父作用域的绑定都可以工作。当我需要更改内容时,我只需销毁子作用域,避免内存泄漏。

我还为子作用域创建了和getter和setter方法,以避免在其他内容使用一次性变量

的情况下对父作用域进行poluting