2014-10-08 20 views
1

DEMO如何在使用模板時獲取指令的原始內容?

考慮到與模板的指令,我怎麼能得到它的原始內容?

例如:

HTML:

<div my-directive> 
    <input type="text"> 
</div> 

JS:

angular.module('App', []).directive('myDirective', function() { 
    return { 
    template: '<div>Template</div>', 
    compile: function(element) { 
     console.log(element.html()); // Outputs <div>Template</div> 
     // How do I get <input type="text"> ? 
    } 
    }; 
}); 

PLAYGROUND HERE

+0

究竟是你想做些什麼?獲取輸入的值並放入div中? – PSL 2014-10-08 23:27:21

+0

我想打印出指令的原始內容。真正的例子有點複雜,所以我試圖想出一個最小的例子。 – 2014-10-08 23:39:43

+0

但最終你希望他們被替換嗎?在你的真實情況下它是否擁有大量的東西?你想對這些內容做任何事嗎? – PSL 2014-10-08 23:48:11

回答

2

因爲你只需要它顯示的目的,而不是真正與綁定和其他東西使用它,在你面前的角度需要它已經觸及它。您可以使用指令的template屬性的函數表達式語法。

實施例: -

var content; 
    template: function(elm){ 
     content = elm.html(); //save the html 
     return '<div>Template</div>'; 
    }, 

用於支撐多個擴展示例: -

.directive('myDirective', function($timeout) { 
    var content={}; 
    var loadedDirs; 
    return { 
    scope:true, 
    template: function(elm){ 
     loadedDirs = loadedDirs || 
        angular.element(document.querySelectorAll('[my-directive]')); 
     //Save the element in its respective index  
     content[loadedDirs.index(elm)] = elm.html(); 

     return '<div>Template<div><pre>{{orig}}</pre></div></div>' 
    }, 
    link: function(scope, element) { 
     var idx = loadedDirs.index(element); 
     scope.orig = content[idx]; 

     //Remove key 
     delete content[idx]; 
     //Remove reference to loadedDirs 
     if(!Object.keys(content)){ 
     loadedDirs = null; 
     } 
     } 
    }; 
}); 

Demo

否Jquery的溶液(工作周圍index

.directive('myDirective', function($timeout) { 
    var content={}, 
     idx = 0; 

    return { 
    scope:true, 
    template: function(elm){ 
     elm.idx = idx; //set an iterative index 
     //Save the element in its respective index  
     content[idx++] = elm.html(); //save element html in a map 

     return '<div>Template<div><pre>{{orig}}</pre></div></div>' 
    }, 
    link: function(scope, element) { 
     var idx = element.idx; //Get idx property value from the element 
     scope.orig = content[idx]; //get the content 
     delete content[idx]; //remove the key 
     if(!Object.keys(content)){ idx = 0; } //reset idx once all are loaded 
    } 
    }; 
}); 

Demo

+0

謝謝!使用模板進行跨分析時,是否有辦法獲取原始HTML?看[這個問題](http://stackoverflow.com/q/26270923/247243) – 2014-10-09 05:27:04

0

可以使用NG-transclude,docs here。您將獲得附加到指令模板內容的原始內容。

0

檢查這個(你必須設置transclude爲true,雖然)

angular.module('App', []).directive('myDirective', function() { 
    return { 
    template: '<div>template</div>', 
    transclude: true, 
    link: function(scope, element, attr, ctrl, transclude) { 
     transclude(scope, function(clone){ 
     var html = ''; 
     for(var i = 0; i<clone.length;i++){ 
      html += clone[i].outerHTML || ''; 
     } 
     console.log(html); 
     }) 

    } 
    }; 
}); 
+3

輸出爲'',而我需要''。 – 2014-10-09 00:45:40

相關問題