AngularJS:如何创建在需要时从 DOM 中添加/删除自身的指令?

Ahm*_*gdi 5 javascript dom angularjs

如果我有一个看起来像这样的自定义模态指令:

return {
  restirct: 'E',
  templateUrl: 'modal.html',
  scope: {
    modalContent: "=",
    modalOpen: "="
  }
}
Run Code Online (Sandbox Code Playgroud)

和 html:

<ng-modal modal-content="content" modal-open"active"></ng-modal>
Run Code Online (Sandbox Code Playgroud)

当 DOM 关闭时,如何确保 DOM 中不存在模态,一旦打开,它就会将自己插入到 DOM 中?我必须将指令插入到 html 中,否则指令将不起作用,但这意味着当我运行应用程序时,模式已经存在于 html 中,即使它没有打开。

我在这里创建了一个 plunker,但它只使用 css 类隐藏/显示模态,而不是完全删除它

编辑:

我在这里创建了另一个版本它实际上从 DOM 中添加/删除了指令。它是基于这样的文章,但它需要分离用于添加/指令和外部控制器(外部控制器手柄添加元素和该指令手柄移除)之间取出该指令的逻辑。我想要指令处理一切,这可能吗?

Twi*_*ron 1

这是你想要的吗?我用一个 div 包装了模板的内容,这样就可以更轻松地在一个变量中获取整个块。然后我根据您想要显示还是隐藏该 div 添加和删除它。

我不相信你可以删除该<ng-modal>元素,但这至少删除了其中的所有内容......

http://plnkr.co/edit/Lr77FuGwcPbojgf3fHuW?p=preview

html

<div>
  <div class="modal hide">
    <h4>{{modalContent.title}}</h4>
    <p>{{modalContent.text}}</p>
    <button ng-click="close()">Close Modal</button>
  </div>

  <div class="modal-overlay"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

js

var ModalDirective = function() {
  return {
    restirct: 'E',
    templateUrl: 'modal.html',
    scope: {
      modalContent: "=",
      modalOpen: "="
    },
    link: function(scope, element, attrs) {
      var modalElements = element.children()[0];
      console.log(element);

      function addModal() {
        console.log('Opening modal');
        element.addClass('open');
        //add the modal elements back into the directive
        if (modalElements) {
          //should be 0
          console.log('Element child count before add', element.children().length);
          element[0].appendChild(modalElements);
           //should be 1
           console.log('Element child count after add', element.children().length);
        }
      }

      function removeModal() {
        element.removeClass('open');
        console.log('Closing modal');
        if (modalElements) {
          //remove the modal elements from the directive
           //should be 1
          console.log('Element child count before remove', element.children().length);
          element[0].removeChild(modalElements);
          //should be 0
          console.log('Element child count after remove', element.children().length);
        }
      }

      scope.$watch('modalOpen', function(newVal, oldVal) {

        if (newVal) {
          addModal();
        } else {
          removeModal();
        }

      });

      scope.close = function() {
        scope.modalOpen = false;
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)