2012-10-02 29 views
27

我發現自己一次又一次地重複相同的代碼片段,是有可能做這樣的事情在AngularJS:是否可以在AngularJS模板中創建可重用的片段?

<div ng-snippet="mySnippet"> 
    This is a snippet 
</div> 

<div ng-snippet="anotherSnippet"> 
    Yet another snippet!! 
</div> 

<ng:include src="anotherSnippet"> 
<ng:include src="anotherSnippet"> 
<ng:include src="mySnippet"> 

和上面會輸出:

Yet another snippet!! 
Yet another snippet!! 
This is a snippet 

我不一定在尋找這個確切的「ng:include」解決方案或模式,但會減少我的模板中的重複。

回答

37
<script type='text/ng-template' id="mySnippet"> 
    This is a snippet 
</script> 

<script type='text/ng-template' id="anotherSnippet"> 
    Yet another snippet!! 
</script> 

<ng-include src="'anotherSnippet'"></ng-include> 
<ng-include src="'anotherSnippet'"></ng-include> 
<ng-include src="'mySnippet'"></ng-include> 

這應該是你想要的。

文件scriptng-include

+0

完美,謝謝! – DaveJ

+0

太棒了。你希望輸入鏈接到不同對象的表單以及輸入的不同名稱的情況如何? https://plnkr.co/edit/iCOIq88e7gSSYaE92b0t?p=preview –

12

這聽起來像你想要使用directives。下面是一個簡單的例子:http://jsfiddle.net/gyF6V/1/

+3

我會去指令包括;他們會讓你的標記更具可讀性。 – btford

+12

每當我看到一個字符串中的html時,我內心的某些東西就感覺不對。 –

+10

如果你不想HTML內的JavaScript,只需使用'templateUrl'屬性而不是'template'並將其指向具有模板的html文件。 – dnc253

相關問題