2012-10-02 32 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

相关问题