是否可以在AngularJS模板中执行可重用的片段?

Dav*_*veJ 27 javascript 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">
Run Code Online (Sandbox Code Playgroud)

而上述的输出将是:

Yet another snippet!!
Yet another snippet!!
This is a snippet
Run Code Online (Sandbox Code Playgroud)

我不一定在寻找这种确切的"ng:include"解决方案或模式,但可以减少模板中的重复.

Ren*_*des 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>
Run Code Online (Sandbox Code Playgroud)

这应该是你想要的.

脚本ng-include的文档.


dnc*_*253 12

这听起来像你想使用指令.这是一个简单的例子:http://jsfiddle.net/gyF6V/1/

  • 每当我在字符串中看到html时,我内心的某些东西感觉不对. (12认同)
  • 如果您不想在javascript中使用html,只需使用`templateUrl`属性而不是`template`并将其指向包含模板的html文件. (10认同)
  • 我会选择包括指令; 它们会让你的标记更具可读性. (3认同)