簡體   English   中英

如何在現有父指令元素和子指令元素之間動態嵌套指令元素?

[英]How to dynamically nest a directive element in-between existing parent and child directive elements?

背景:

我正在使用自定義CMS,我對代碼庫的訪問權限有限。 因此,在少數情況下,我計划使用JavaScript進行一些DOM操作。

問題:

我有一個容器指令,容器有普通的舊HTML項,但是無法將這些項標記為來自服務器端的指令。 此外,普通的舊HTML項包含作為指令的子內容。

例:

這是以前的:

DIV[container-directive]

  DIV.some-item-in-html
    DIV[some-directive-in-the-content]


  DIV.some-item-in-html
    DIV[some-directive-in-the-content]

  ...

以下是DOM之后應該是什么樣子:

DIV[container-directive]

  DIV[container-item]       <-- This is what needs to be inserted

    DIV.some-item-in-html
      DIV[some-directive-in-the-content]

  DIV[container-item]       <-- This is what needs to be inserted

    DIV.some-item-in-html
      DIV[some-directive-in-the-content]

  ...

題:

有沒有人有關於注入DOM元素的最佳方法的建議,這些方法是使用JavaScript嵌套指令之間的指令?

一些想法:

我認為在編譯之前通過angular操縱DOM,但我想知道在Angular框架中是否有辦法做到這一點。

另一個選項是從容器指令的后連接函數,我可以將HTML項目包裝在名為“container-item”的指令元素中,然后$手動編譯項目。 所以,我嘗試了這個,但是我得到了一個錯誤,該錯誤與已經包含了被轉換內容的指令相關。 關於“ngTransclude”出乎意料的事情。 我認為這與已經處理的內部指令有關。

我會選擇你的第一個選項並在角度編譯之前操縱DOM。

您可以在包含要操作的元素的指令中執行此操作。

例如:

app.directive('body', function() {
    return {
        restrict: 'E',
        compile: function(element, attr) {
            // find the inner element and wrap it
            $('.some-item-in-html', element).wrap('<div class="container"></div>');
        }
    }
});

父指令總是在子指令之前編譯,因此您可以在編譯屬性中更改子節點的DOM,而不必擔心重新編譯或重新鏈接指令。

[編輯]

感謝Biagio進行以下編輯。

此方法不應與帶有模板的指令一起使用,因為該元素將分配給模板而不是子元素。

另一種方法是在角度生命周期開始時運行的函數中進行DOM操作。

例如:

 app.run(function(){
       // find the inner element and wrap it
      $('.some-item-in-html').wrap('<div     class="container"></div>');
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM