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>
2
  • 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. Commented Aug 4, 2014 at 19:54
  • See here Commented Aug 4, 2014 at 21:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.