htmlangularjsngsanitize

Displaying html via angular


I'm trying to show the html that has been encoded. but this doesn't seem to work. input is via:

<h1>Some header</h1>

and it shows:

<h1>Some header</h1>

But I want it to render the html; but as shown in the following pen; it just show the source html

this is my current controller:

var myApp = angular.module('myApp', ['ngSanitize']);

myApp.controller('myCtrl', function ($scope, $sce) {
  $scope.trustedHtml = $sce.trustAsHtml('&lt;h1&gt;Some header&lt;/h1&gt;');
});

with the following html:

<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-bind-html="trustedHtml"></div>
</div>

http://codepen.io/cskiwi/pen/PqXdOa


Solution

  • To decode the html, you can use this trick:

    var encodedHtml = '&lt;h1&gt;Some header&lt;/h1&gt;';
    var decodedHtml = angular.element('<div>').html(encodedHtml).text();
    

    Then apply to your property:

    $scope.trustedHtml = $sce.trustAsHtml(decodedHtml);