1

For example I have a template and in that template I want to show

<div></div>

I want it to be displayed as above rather than rendering the actual div

Aaron Lumsden
  • 424
  • 1
  • 5
  • 21

3 Answers3

3

according to the Angular.js documentation for $sanitize:

there are 3 options for ng-bind.

  1. ng-bind-html - will output sanitized html, not escaped, which will render normally. JavaScript and other "unsafe" elements are stripped. <div>Raw HTML</div> will render Raw HTML.
  2. ng-bind-unsafe - will bypass $sanitize and output an HTML element verbatim, not escaped. including any potentially unsafe scripts.
  3. ng-bind - will output sanitized, escaped HTML. <div>Raw HTML</div> will output &lt;div&gt;Raw HTML&lt;/div&gt;. The browser will render <div>Raw HTML</div>

Based on your request, #3 would be most appropriate.

Community
  • 1
  • 1
Claies
  • 22,124
  • 4
  • 53
  • 77
1

Create a directive to display the nested HTML as text: http://jsfiddle.net/6j0wqnvf/1/

module.directive('renderNestedHtml', function() {
    return {
        compile: function(element, attrs) {
            var rawHtml = element[0].innerHTML;
            var code = angular.element('<pre></pre>');

            code.text(rawHtml.trim());
            element.replaceWith(code);
        },
    }
})
Enzey
  • 5,254
  • 1
  • 18
  • 20
0

You'll want to use $sanitize.

Either this way:

function MyCtrl ( $scope, $sanitize ) {
    $scope.rawHtml = "<div><script></script></div>";
    $scope.sanitizedHmtl = $sanitize( $scope.rawHtml );
}

or

<div ng-bind-html="rawHtml"></div>
<div ng-bind-html-unsafe="sanitizedHtml"></div>

In a directive, insert the sanitized HTML:

element.html( scope.sanitizedHtml );

See this answer for more info - it's where I got this info from.

Community
  • 1
  • 1
Alex K
  • 8,269
  • 9
  • 39
  • 57