I'm looking at ways to format templates in AngularJS directives. The most common are:
Inline:
// Directive.js
app.directive('flipCard', [
function() {
return {
template:
"<div class='cardslot' ng-class='{\"switch\":shouldFlip}'> \
<card-side candidate-model='currentCandidate' class='card-a-side'></card-side> \
<card-side candidate-model='nextCandidate' class='card-b-side'></card-side> \
</div>"
};
}
]);
Advantages:
- keeps all directive code in 1 file (cleaner)
- doesn't require an extra file to be loaded at runtime
Disadvantages:
- hard to format, ugly
- no code completion, no tag highlighting
- nesting " in ' in " and ' might become complicated
External
// Directive.js
app.directive('directive', [
function() {
return {
templateUrl: '/views/partials/directive.html'
};
}
]);
// Directive.html
<div class="cardslot" ng-class="{'switch':shouldFlip}">
<card-side candidate-model="currentCandidate" class="card-a-side"></card-side>
<card-side candidate-model="nextCandidate" class="card-b-side"></card-side>
</div>
Advantages:
- cleaner formatting
- code highlighting & code completion
- cleans up directive code by removing html tags and keeping the javascript
Disadvantages:
- needs an extra file per directive (while coding & at runtime)
- might feel as overkill with smaller template code
That's some in column A and some in column B. So how do I choose between them? When is inline formatting preferable and when is external formatting preferable?
More generally, should I be considering other methods?
In my project I do the both methods at the same time ;) :
development : It's good practice to have a separate file for each templates (with module subfolder if needed) because it's simplier to maintain and for readability.
runtime/ packaging-build : I use html2js to real-time replace my templateUrl string by the template content.
Verbose code, optimised generated code, less HTTP hits, cached templates, etc ...