Filippo oretti
Filippo oretti

Reputation: 49817

How to print html string as html

If just for example I do:

var = "<a>Asd</a>";

<span>{{ var }}</span>

The string is printed like text and not as html, so how do I print the html ?

Upvotes: 29

Views: 50938

Answers (3)

Wellington Lorindo
Wellington Lorindo

Reputation: 2465

Before using the ng-bind-html directive you must include the $sanitize service or it will throw an error.

Error: $sce:unsafe Require a safe/trusted value Attempting to use an unsafe value in a safe context.

Error: [$sce:unsafe] http://errors.angularjs.org/1.4.5/$sce/unsafe
    at Error (native)

The right way:

<script src="angular.js"></script>
<script src="angular-sanitize.js"></script>
var myApp = angular.module('app', ['ngSanitize']);
myApp.controller('MyController', ['$scope', function($scope) {
  $scope.myHTML = '<a href="#">Hello, World!</a>';
}]);
<div ng-controller="MyController">
 <p ng-bind-html="myHTML"></p>
</div>

https://docs.angularjs.org/api/ngSanitize

https://docs.angularjs.org/api/ng/directive/ngBindHtml

Upvotes: 10

Adam Kosmala
Adam Kosmala

Reputation: 935

You can also try something like that:


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

and then, in view:


    ng-bind-html=" myHTML | to_trusted"

Upvotes: 6

Florian F.
Florian F.

Reputation: 4700

You should be using ng-bind-html directive.

Creates a binding that will innerHTML the result of evaluating the expression into the current element in a secure way.

<ANY ng-bind-html="{expression}">
   ...
</ANY>

Upvotes: 42

Related Questions