1

Please find the plnkr

I want to display some html preview. The html is already sanitized at the server (for eg: "<b>HELLO</b>"). How can I display the html form. In the example, I want to display myHtml2 as displayed for myHtml (first preview).

html

 <div ng-controller="myController">
      <div ng-bind-html="myHtml"></div>
      <div ng-bind-html="myHtml2"></div>
      <div >{{myHtml2}}</div>
    </div>

js

myApp.controller('myController', ['$scope', '$sce', function myController($scope, $sce){
  $scope.myHtml = "<b>HELLO</b>";
  $scope.myHtml2 = "&lt;b&gt;HELLO&lt;/b&gt;";      
}]);

out

HELLO
<b>HELLO</b>
&lt;b&gt;HELLO&lt;/b&gt;

1 Answer 1

1

You just need to use $sce.trustAsHtml and unsanitize HTML on your client: http://plnkr.co/edit/h2loxWsPJOELhNvkfHmK?p=preview

// From: https://stackoverflow.com/questions/1912501/unescape-html-entities-in-javascript
function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

myApp.controller('myController', ['$scope', '$sce', function myController($scope, $sce){
  $scope.myHtml = "<b>HELLO</b>";
  $scope.myHtml2 = $sce.trustAsHtml(htmlDecode("&lt;b&gt;HELLO&lt;/b&gt;"));

}]);

htmlDecode from: Unescape HTML entities in Javascript?

However, I would not recommend taking this approach. It feels very hackish and I suspect could lead to vulnerabilities on your site.

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

3 Comments

thanks for showing this approach. So, what would you recommend? keep the html unescaped at the server, and only sanitize through Angular at client side? I am curious site like SO, how do they handle this situation. Do they just store markdown, and convert at the client?
@bsr SO uses wmd and renders the Markdown purely on the client side. I would keep the HTML on the client side (or provide partials from separate paths from the server) and fetch data using separate API and interpolate the data in using Angular bindings.
just read blog.stackoverflow.com/2008/06/safe-html-and-xss , but not sure what was the final solution as the linked site is down, and it is a post from 08

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.