title: How to conditionally apply a template via custom Angular directives?
body: <p><kbd><a href="http://plnkr.co/edit/R7E7IcJjvpAg8ddbZLNt?p=preview" rel="noreferrer"><strong>DEMO</strong></a></kbd></p>
  
  <p>Consider the following directive:</p>
  
  <pre><code>angular.module('MyApp').directive('maybeLink', function() {
    return {
      replace: true,
      scope: {
        maybeLink: '=',
        maybeLinkText: '='
      },
      template: '&lt;span&gt;' + 
                '  &lt;span ng-hide="maybeLink" ng-bind-html="text"&gt;&lt;/span&gt;' +
                '  &lt;a ng-show="maybeLink" href="#" ng-bind-html="text"&gt;&lt;/a&gt;' +
                '&lt;/span&gt;',
      controller: function($scope) {
        $scope.text = $scope.maybeLinkText.replace(/\n/g, '&lt;br&gt;');
      }
    }; 
  });
  </code></pre>
  
  <p>The directive adds both the <code>&lt;span&gt;</code> and the <code>&lt;a&gt;</code> to the DOM (only one is visible at a time).</p>
  
  <p>How could I rewrite the directive such that it will add <strong>either <code>&lt;span&gt;</code> or <code>&lt;a&gt;</code></strong> to the DOM, but not both?</p>
  
  <hr>
  
  <p><strong>UPDATE</strong></p>
  
  <p>OK, I guess I could use <code>ng-if</code> like that:</p>
  
  <pre><code>template: '&lt;span&gt;' + 
            '  &lt;span ng-if="!maybeLink" ng-bind-html="text"&gt;&lt;/span&gt;' +
            '  &lt;a ng-if="maybeLink" href="#" ng-bind-html="text"&gt;&lt;/a&gt;' +
            '&lt;/span&gt;'
  </code></pre>
  
  <p>But, how could one get rid of the surrounding <code>&lt;span&gt;</code> in this case?</p>
  
  <hr>
  
  <p><strong>UPDATE 2</strong></p>
  
  <p>Here is a version of the directive that uses <code>$compile</code>. It doesn't have the surrounding <code>&lt;span&gt;</code>, but the two way data binding doesn't work either. I'm really interested to know how to fix the two way data binding issue. Any ideas?</p>
  
  <p><kbd><a href="http://plnkr.co/edit/HkqIQ7fkSbv2RD6JNd00?p=preview" rel="noreferrer">DEMO</a></kbd></p>
  
  <pre><code>angular.module('MyApp').directive('maybeLink', function($compile) {
    return {
      scope: {
        maybeLink: '=',
        maybeLinkText: '='
      },
      link: function(scope, element, attrs) {
        scope.text = scope.maybeLinkText.replace(/\n/g, '&lt;br&gt;');
  
        if (scope.maybeLink) {
          element.replaceWith($compile('&lt;a href="#" ng-bind-html="text"&gt;&lt;/a&gt;')(scope));
        } else {
          element.replaceWith($compile('&lt;span ng-bind-html="text"&gt;&lt;/span&gt;')(scope));  
        } 
      } 
    }; 
  });
  </code></pre>