Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

append as html in angular

I want to append the value as html in angular

<div class="storycontent" ng-class="{show: show}">
       <a href="#/profile?{{review.id}}">{{review.name}}</a>: {{review.story}}
</div>

Here in the {{review.story}} I will have value like <b>hello</b><i>something</i> etc

The problem is its displaying the content as <b>hello</b><i>something</i> instead of hellosomething (ie the styling is not applied) I have to use jQuery to do this

$(".content").each(function () {
    $(this).html($(this).text())
});

How can i directly append as .html() instead of .text() in angular?

Upvotes: 1

Views: 255

Answers (4)

Pierre-Alexandre Moller
Pierre-Alexandre Moller

Reputation: 2354

You don't even need Jquery for that. ng-bind-html can do the trick by himself.

<div class="storycontent" ng-class="{show: show}">
  <a href="#/profile?{{review.id}}">{{review.name}}</a>: 
    <span ng-bind-html="review.story"></span>
</div>

Moreover, it's also better to add this on your controller when you get the value. Because without this, ng-bind-hmtl isn't safe.

$scope.review.story = $sce.trustAsHtml($scope.review.story);

Note : $sce have to be injected in your controller. It's not available directly with angularJS.

.controller('ControllerName', ['$scope', '$sce', function($scope, $sce) {... 

Upvotes: 4

lucas
lucas

Reputation: 153

You can use directive ngBindHtml, more info here: https://docs.angularjs.org/api/ng/directive/ngBindHtml

Also you have to remeber that before binding html you have to ensure Angular that it is safe. You can use ngSanitize for it and $sce.trustAsHtml function:

https://docs.angularjs.org/api/ng/service/$sce#trustAsHtml

Upvotes: 2

sahil gupta
sahil gupta

Reputation: 2349

You can use ng-bind-html in angular.

By Docs: ng-bind-html

Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default, the resulting HTML content will be sanitized using the $sanitize service. To utilize this functionality, ensure that $sanitize is available, for example, by including ngSanitize in your module's dependencies (not in core Angular). In order to use ngSanitize in your module's dependencies, you need to include "angular-sanitize.js" in your application.

Use: ng-bind-html="review.story">

Refer docs

Upvotes: 1

atinder
atinder

Reputation: 2090

use ng-bind-html="expression" expression is your html here

Upvotes: 1

Related Questions