簡體   English   中英

從動態html編譯Angular指令

[英]Compile Angular directive from dynamic html

我似乎無法完成這項工作:我有從ng-repeat編譯的HTML,我也想編譯其結果。 我將如何處理?

我有一個包含大塊文本的數據集,這些文本被賦予了顯示類型。 將此類型設置為跨度類。 大多數類型只是觸發CSS規則(例如,注釋樣式框,請參見屏幕截圖),但其他類型應調用指令。 例如,包含“名為Nicodemus,”的塊是隱藏類型的。 我有一個指令,可以折疊該塊並插入一個小按鈕以對其進行擴展。

碼:

<span class="chunk type-{{chunk.type}}" ng-repeat="chunk in verse.chunks">{{chunk.text}}</span>

結果像

<span class="chunk type-hidden">named Nicodemus, </span>

如果第二個是我的源html,它將編譯typeHidden指令就好了。 我想我需要找到一種方法進行第二次角度編譯。 我似乎無法使用$ compile來完成它(盡管我想我不太了解它是如何工作的)。

希望能對您有所幫助!

屏幕截圖

提前致謝!

這是一個小巧的例子 ,展示了如何獲取指令來編譯元素,然后再次編譯。

懶惰的代碼:

angular
    .module('App')
    .directive('compileTwice', compileTwiceFactory);

function compileTwiceFactory($compile) {

    return {
        restrict: 'AE',   // Whatever you want
        terminal: true,   // Angular should not keep compiling the element
                          // by itself after encountering this directive!
        compile: compile, // Instead, we tell Angular how to compile the rest of the element
        priority: 1001,   // This directive should get compiled before the others, obviously
    };

    function compile(element, attrs) {
        element.removeAttr('compile-twice');
        element.removeAttr('data-compile-twice');

        return function postLink(scope, _element, _attrs) {
            var compiledTwice = $compile($compile(_element)(scope)[0])(scope)[0];
            // do something with compiledTwice
        };
    }

}

編輯:顯然,您可以將其概括為可以指定的任意次數,如下所示:

<div compile-n-times="420"></div>

編輯:在Firefox下似乎無法使用插件?

實際上,我已經能夠通過解決方法解決此問題。 不那么優雅,但是如果我將指令嵌套在ngrepeat中並對名稱進行硬編碼,則可以使用ng-if使它可見。

<!-- special type hidden -->
      <span ng-if="chunk.type=='hidden'">
        <span class="type-hidden">
          {{chunk.text}}
        </span>
      </span>

暫無
暫無

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

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