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

后端 未结 3 664
甜味超标
甜味超标 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');
                }
            }
        };
    });
    

提交回复
热议问题