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

Asked

Viewed 107 times

0

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

Behold:

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>

If I do with the A or E (to read attributes or elements respectively), it works perfectly:

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 the directive with restriction M did not work in the first example?

2 answers

3


A comment cannot have child elements. However, you can compile the resulting element from the controller 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>

2

As a complement to Onosendai’s reply, I would like to add that by adding the property replace: true, the Directives with restriction M start working with template.

Behold:

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.