Ways of formatting an AngularJS directive template

767 views Asked by At

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?

2

There are 2 answers

0
Jscti On

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 ...

1
koolunix On

There is a third way, which I prefer, to use templateUrl to reference the id of an element within your existing markup. IMHO I think it's more consistent with the declarative approach of Angular

<div ng-app="pageModule"
    ng-controller="parentCtrl">
    <script type="text/ng-template" id="myTemplate">
        <span ng-click="remove()">{{label}}</span>
    </script>
    <div my-directive></div>
</div>



var pageModule = angular.module('pageModule',[])
.controller('parentCtrl',function($scope) {
})
.directive('myDirective',function() {
    return {
        restrict : 'A',
        templateUrl : 'myTemplate'