Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering HTML in a <div> - AngularJS

Tags:

angularjs

So I have the following div and what I'd like to do, is have the div render HTML if it exists inside {{statusUpdate.text}}.

What I've done, is wrap the usernames in the span you see below - but I'd like it to be rendered as actualy HTML, today it's just the HTML in plain text.

<div ng-repeat="statusUpdate in statusUpdates | orderBy:'-time'">
  <div class="actContent">{{statusUpdate.text}}</div>
</div>

Currently I just get this as output - see below - and this is the output in the browser

enter image description here

<div class="actContent ng-binding">hello &lt;span class='mentionedUserTag'&gt;Aref Abedi&lt;/span&gt; how are you?
</div>

Any ideas on how to solve this?

like image 757
user2656127 Avatar asked Feb 26 '14 15:02

user2656127


2 Answers

Use ng-bind-html:

<div ng-repeat="statusUpdate in statusUpdates | orderBy:'-time'">
  <div class="actContent" ng-bind-html="statusUpdate.text"></div>
</div>

Don't forget to add ngSanitize, which is in a different js file (angular-sanitize.js):

app.module('app', ['ngSanitize']);
like image 120
asgoth Avatar answered Sep 27 '22 21:09

asgoth


AngularJS escapes html by default. To render the HTML you have to use ng-bind-html like this:

<div ng-repeat="statusUpdate in statusUpdates | orderBy:'-time'">
  <div class="actContent" ng-bind-html="statusUpdate.text"></div>
</div>

You might get an error like:
Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.
Use $sce.trustAsHtml(input) in your controller or filter to fix this.

like image 37
Frederik Kammer Avatar answered Sep 27 '22 21:09

Frederik Kammer