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

后端 未结 3 665
甜味超标
甜味超标 2021-02-05 07:17

What I need is the functionality of two ng-views. Because I can\'t I want to change the innerHTML of something and compile it. The problem I have is when I change the content ag

相关标签:
3条回答
  • 2021-02-05 07:28

    Thanks for you good solution. I've just posted some implement code

    .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');
                }
            }
        };
    });
    
    0 讨论(0)
  • 2021-02-05 07:31

    The solution for this problem is creating a new child scope. All bindings with parent scope work because of scope Inheritance. When I need to change the content, I simply destroy the child scope, avoiding memory leaks.

    I've also made and getter and setter methods for the child scope to avoid poluting que parent scope, in case the other content uses disposable variables

    0 讨论(0)
  • 2021-02-05 07:38

    To manually remove the element do an element.remove(). Sounds like you also want to destroy the scope of your compiled element so you can do that too by doing scope.$destroy(); or $scope.$destroy(); depending on if you're in a directive or not.

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

    0 讨论(0)
提交回复
热议问题