5

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?

3 Answers 3

13

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']);
Sign up to request clarification or add additional context in comments.

2 Comments

why did this situation require sanitize
@dsdsdsdsd Because by default, the resulting HTML content will be sanitized using the $sanitize service to remove dangerous code if present. You can read more about this in the official page.
1

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.

2 Comments

So, I got that exact error just now. Could you point me in the right direction regarding the controller? I'm unsure how to implement.
For that, you need to add ngSanitize as a submodule.
0

use ng-bind-html directive

API ref - http://docs.angularjs.org/api/ng/directive/ngBindHtml

<div class="actContent" ng-bind-html="statusUpdate.text"></div>

1 Comment

Ok great, but what would I use as the expression? ng-bind-html="expression" Thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.