28

I'm finding myself repeating the same snippets of code again and again, is it possible to do something like this in 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.

2 Answers 2

39
<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 script and ng-include.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. What about a form where you want inputs to link to different objects, and different names for the inputs? plnkr.co/edit/iCOIq88e7gSSYaE92b0t?p=preview
12

This sounds like you want to use directives. Here is a simple example: http://jsfiddle.net/gyF6V/1/

3 Comments

I'd go with directives over includes; they'll make your markup more readable.
Whenever I see html inside a string, something inside me just doesn't feel right.
If you don't want html inside the the javascript, just use the templateUrl property instead of template and point it to the html file that has your template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.