How to use template in directives with restrict M (comments)?

0

I am trying to use the restrict option with the value 'M' (for angular work through comments) to create a directive. But the comment is not embedding the value I'm adding in template .

See:

angular.module('example', [])
.directive('stackoverflow', function () {

    return {
         restrict: 'M',
         template: '<div>my name is wallace</div>'
    };
});
<div ng-app="example">
    <!-- directive: stackoverflow -->
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>

IfIdowithAorE(toreadattributesorelementsrespectively),itworksperfectly:

angular.module('example', [])
.directive('stackoverflow', function () {

  return {
    restrict: 'AE',
    template: '<div>my name is wallace</div>'
  };
});
<div ng-app="example">
  <div stackoverflow></div>
  <stackoverflow></stackoverflow>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>

Why did not the directive with M work in the first example?

    
asked by anonymous 01.09.2016 / 19:04

2 answers

3

A comment can not have child elements. However you can compile the element resulting from the controller evaluation after the comment itself:

angular.module('example', [])
.directive('stackoverflow', function ($compile) {

    return {
         restrict: 'M',
         template: '<div>my name is wallace</div>',
         link: function (scope, element, attrs)
         {
             console.log(element[0].innerHTML);
             element.after($compile(element[0].innerHTML)(scope));
         }
    };
});
<div ng-app="example">
    <!-- directive: stackoverflow -->
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    
01.09.2016 / 19:30
2

As a complement to OnoSendai's response, I would like to add that by adding the replace: true property, policies with M will start working with template.

See:

angular.module('example', [])
.directive('stackoverflow', function () {

  return {
    replace: true,
    restrict: 'M',
    template: '<div>my name is wallace</div>'
  };
});
<div ng-app="example">
  <!-- directive: stackoverflow -->
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    
01.09.2016 / 21:09