Naveen
Naveen

Reputation: 777

How to bind html tags in html using angular

HTML

<div><code><pre>{{out_html}}</pre></code></div>

AngularJS

$scope.out_html = "<p style='color:red'>John Smith</p>";

I want to show that 'p' tag name "John smith" in red color in html browser. But here it's showing html code instead of red color `John Smith.

plunker

Upvotes: 0

Views: 1947

Answers (5)

Shailesh Ladumor
Shailesh Ladumor

Reputation: 7242

you can user ng-bind-html directive for binding a html in angular js,

here is your working plunker

<code>
      <pre>
        <p ng-bind-html="out_html"></p>
      </pre>
</code>

Upvotes: 1

Christian Meyer
Christian Meyer

Reputation: 1771

This is a safety precaution from angularjs. This is to ensure unwanted behaviour. So Angular will always escape the tags for you. What you can do is use ng-bind-html but what's very important is that you first "allow" this string to be interpreted as HTML that works with trustAsHtml.

angular.module('test', []).controller('ctrl', function($scope, $sce) {
  $scope.out_html = "<p style='color:red'>John Smith</p>";
  $scope.trust = $sce.trustAsHtml;
});

<span ng-bind-html="trust(out_html)"></span></div>

Here is also another thread of that problem: https://stackoverflow.com/a/28444859/8196542

Upvotes: 0

wawka
wawka

Reputation: 5144

Yes, Angular sanitizes binded expressions by default. To prevent that you can use ngBindHtml: https://docs.angularjs.org/api/ng/directive/ngBindHtml.

However, if this is just a matter of styling, why don't you use ngClass ? https://docs.angularjs.org/api/ng/directive/ngClass

Upvotes: 1

Richard
Richard

Reputation: 449

You can separate your p tag value and p color, just add another variable/scope

HTML

<div><code><pre><p style='color:{{color}}'>{{value}}</p></pre></code></div>

AngularJS

$scope.value = "John Smith";
$scope.color = "red";

Upvotes: 0

Najam Us Saqib
Najam Us Saqib

Reputation: 3404

You can bind it like:

<div>
  <code>
    <pre ng-bind-html="out_html" style="color:red;"></pre>
  </code>
</div>

For Color you can style <pre> element.

The ng-bind-html directive is a secure way of binding content to an HTML element. For more Details: https://www.w3schools.com/angular/ng_ng-bind-html.asp

Upvotes: 2

Related Questions