1

I'm trying to pass html code to an angular directive as a parameter. Is this possible?

Here's the directive in the html. Inside the directive, the <br><br> comes out in plain text.

<mbs-are-you-sure body-text="'You are exporting to: ' + environmentsPretty + '.<br><br> You will replace all books.'"></mbs-are-you-sure>

And here's the directive:

.directive('mbsAreYouSure', [function() {
    return {
        restrict: 'E',
        scope: {
            bodyText: '='
        },
        templateUrl: 'directive-templates/are-you-sure.html'
    };
}]);

And the template:

<div>{{bodyText}}</div>
CorayThan
  • 17,174
  • 28
  • 113
  • 161
  • Value of any attribute is text according to w3cs. It cannot be html. Now it is another thing to take this text and display it somewhere as HTML. During that process you can set the inner html of that particular element intended to display the "html contents" currently a string. If you plan to construct this html as angular directives or with bindings you need to $compile the element before attaching. – bhantol Aug 04 '14 at 19:54
  • See [here](http://stackoverflow.com/questions/15754515/how-to-render-html-with-angular-templates) – JoshuaJ Aug 04 '14 at 21:06

1 Answers1

1

You can modify your directive to bind to html and use $sce to "convert" the plain text to html (it's more like a trust issue lol).

Here is a plunkr with a working example: http://plnkr.co/edit/AB95oCiC3yzJTwkeVeUm

.directive('mbsAreYouSure', [
  function() {
    return {
      restrict: 'E',
      scope: {
        bodyText: '='
      },
      template: '<div>Plain Text:<br/> {{bodyText}}</div><br/>Converted: <p ng-bind-html="teste"></p>',
      controller: function($scope, $sce) {

        $scope.$watch('bodyText', function(value) {
          $scope.teste = $sce.trustAsHtml(value);
        })

      }
    };
  }
]);

There may be other ways to do this, perhaps more elegant, but this is the quickest I could do on top of my head.

Hope that helps, thanks.

Fedaykin
  • 4,482
  • 3
  • 22
  • 32
  • 1
    Finally got around to trying it out, and this worked like a charm. Now to read up on `$sce` so I can actually understand what I did! – CorayThan Aug 08 '14 at 17:40