2015-09-18 120 views
0

我似乎無法完成這項工作:我有一個由ng-repeat編譯的HTML,我也想編譯這個結果。我會怎麼做呢?從動態html編譯Angular指令

我有一個包含文本塊的數據集,它已經被賦予了顯示類型。這種類型被設置爲跨度類。大多數類型只是觸發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完成它(儘管我想我不太明白這是如何工作的)。

希望你能幫助!

Screenshot

提前感謝!

+0

你想完成什麼? Angular會自動地在ng-repeat中「編譯」指令,通常不需要明確地告訴它將其遞減到較低的級別。也許如果你告訴我們關於你的'typeA'指令想要做什麼的一些事情,你會問什麼更清楚? –

+0

真的沒什麼特別。它隱藏了內容並添加了一個小按鈕使其再次可見。它看起來好像不認爲type-a是需要編譯爲指令的東西。 – Jurgen

+0

只要添加一個'type-a'類並不會自動使它成爲一個指令。事實上,你需要編譯。但是,你能解釋一下爲什麼你需要這個動態指令嗎?你不能使用一個通用的指令,其行爲有所不同,取決於它的類型?爲了避免XY問題,你能解釋一下(在問題的正文中)你正在努力完成什麼?有可能是更自然的方式來做到這一點 –

回答

0

Here's a plunker顯示如何獲得指令來編譯元素,然後再次。

對於懶人代碼:

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下工作?

+0

看起來很有希望,但我似乎無法得到它的工作,可能是因爲我的元素是一個ng-repeat元素。 $ compile(_element)(scope)[0]返回<! - ngRepeat:chunk in verse.chunks - >而不是元素HTML – Jurgen

+0

在你的活動中,看看使用

abcdef
Jurgen

+0

@Jurgen會發生什麼哦,那是因爲角指令編譯爲註釋+實際編譯的元素。如果你檢查一個使用角度的頁面的標記,你會看到那些'<! - ng-if =「...」 - >'和'<! - ng-repeat =「...」 - >'無處不在的評論(除非可能有禁用它們的選項?)。所以是的,而不是做'[0]',當指令的行爲像你期望的那樣並且只輸出編譯後的元素時,你應該在數組中尋找你需要的實際元素,最重要的是通過標籤名稱。簡單。 – jrsala

0

我實際上已經能夠解決這個問題。不夠優雅,但是如果我在ngrepeat中嵌套我的指令並對其名稱進行硬編碼,則可以使用ng-if使其可見。

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