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

时间:2013-05-28 16:36:40

标签: javascript dom angularjs

我需要的是两个ng-views的功能。因为我不能想要改变某些东西的innerHTML并编译它。我遇到的问题是当我再次更改内容时,我可以编译,但是会自动删除绑定,或者我必须手动执行,如果是这样,怎么做?

编辑:解释

我想创建一个模态,我可以更改其内容并绑定到不同的范围(因此$ compile)。但是我不想破坏整个模态,只是破坏它的一些内容,而是变成另一个。我的主要疑问是,如果通过删除一些已编译的HTML,它可能会导致内存泄漏。

解决

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

3 个答案:

答案 0 :(得分:20)

要手动删除元素,请执行element.remove()。听起来你也想破坏编译元素的范围,所以你也可以通过scope.$destroy();$scope.$destroy();来做,这取决于你是否在指令中。

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

答案 1 :(得分:9)

谢谢你的好解决方案。我刚发布了一些实施代码

.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');
            }
        }
    };
});

答案 2 :(得分:3)

此问题的解决方案是创建一个新的子范围。由于范围继承,所有与父范围的绑定都起作用。当我需要更改内容时,我只是破坏子范围,避免内存泄漏。

我还为子作用域制作了getter和setter方法,以避免对que父作用域进行限制,以防其他内容使用一次性变量