1

suppose I have this bit of html and javascript:

$scope.test = "hello<br/>world";
<div>{{ test }}</div>

angular will obviously render it as:

<div>hello<br/>world</div>

and that is exactly how it is supposed to work but, what if I would like it to actually render it as html markup rather than text?

I know this can lead to security problems, but I would just like to know out of curiousity.

Thanks in advance.

user3721031
  • 57
  • 1
  • 1
  • 6

2 Answers2

4

You can use the ng-bind-html directive in AngularJS.

<div ng-controller="ngBindHtmlCtrl">
 <p ng-bind-html="trustedHtml"></p>
</div>

where

$scope.myHTML = "I am an <code>HTML</code>string with <a href="#">links!</a>"

will be rendered accordingly.

For the security concerns involved in this, before you pass the HTML content to your scope variable myHTML, sanitize it with:

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

and then use $scope.trustedHtml in your ng-bind-html directive as listed above.

akskap
  • 803
  • 6
  • 12
0

You can create a filter as suggested here:

HTML :

<div ng-controller="MyCtrl">
  <div ng-bind-html="my_html | to_trusted"></div>
</div>

This is how your javascript would appear:

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

angular.module('myApp')
    .filter('to_trusted', ['$sce', function($sce){
        return function(text) {
            return $sce.trustAsHtml(text);
        };
    }]);

function MyCtrl($scope) {

    $scope.my_html = '<div>hello<br/>world</div>';
}
Community
  • 1
  • 1
skolte
  • 367
  • 2
  • 9