Angular JS: How to display a String variable in HTML

shape
shape
shape
shape
shape
shape
shape
shape

Before version 1.2 of Angular JS it was possible to use the following directive:

<p ng-bind-html-unsafe="chamado.descricao"></p>

However, this directive was removed in later versions for security reasons.

How to display a variable in HTML without escaping the tags ?

1 – In your Controller pass the $scope and $sce variables.

var MeuCtrl = function($scope, $sce) {

}

2 – We will create a function that will be used in the View to allow a String to be displayed in HTML:

var MeuCtrl = function($scope, $sce) {
    $scope.chamados = [{id: "1", descricao:"<b>blog.masterdaweb.com</b>"}]
    $scope.trustAsHtml = function(string) {
         return $sce.trustAsHtml(string);
    };
}

3 – Then the View looks like this:

<li ng-repeat="chamado in chamados">
    <p data-ng-bind-html="trustAsHtml(chamado.descricao)"></p>
</li>

The “called.description” object containing the HTML is passed to the“$sce.trustAsHtml()” function, which allows HTML to be displayed in the View.

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest news

Latest news directly from our blog.