javascript 是否可以在 AngularJS 模板中执行可重用的片段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12698796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to do reusable snippets within AngularJS templates?
提问by DaveJ
I'm finding myself repeating the same snippets of code again and again, is it possible to do something like this in 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">
and the output of the above would be:
上面的输出将是:
Yet another snippet!!
Yet another snippet!!
This is a snippet
I'm not necessarily looking for this exact "ng:include" solution or pattern but something that would reduce the repetition in my templates.
我不一定要寻找这种确切的“ng:include”解决方案或模式,而是会减少模板中重复的东西。
回答by Renan Tomal Fernandes
<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>
This should be what you want.
这应该是你想要的。
Docs for scriptand ng-include.
脚本和ng-include 的文档。
回答by dnc253
This sounds like you want to use directives. Here is a simple example: http://jsfiddle.net/gyF6V/1/
这听起来像是您想使用指令。这是一个简单的例子:http: //jsfiddle.net/gyF6V/1/