Terry
Terry

Reputation: 14219

Decoding HTML in an AngularJs expression

What's the best way to decode HTML that is contained in strings passed to an Angular expression?

Example:

If I have a string returned from the server like this:

var some_val = "Hello <strong>World</strong>!"

How can I have it render the HTML rather than display it as text?

<!-- Renders to Hello <strong>World</strong>! -->
<span>{{ some_val }}</span>

Update: Here's actual use case in a repeater:

Works (unsanitized)

<div ng-repeat="category in some_list">
   <p>{{ category.name }}</p>
   <p ng-repeat="bullet in category.bullets">{{ bullet.desc }}</p>
</div>

Doesn't work at all

<div ng-repeat="category in some_list">
   <p ng-bind-html="category.name"></p>
   <p ng-repeat="bullet in category.bullets" ng-bind-html="bullet.desc"></p>
</div>

Upvotes: 24

Views: 28836

Answers (1)

Tiago Rold&#227;o
Tiago Rold&#227;o

Reputation: 10649

As described here, in the docs:

<span ng-bind-html="some_val"></span>

Remember that some_val must be a angular model (basically, a $scope.some_val must exist somewhere in your app)

EDIT:

I should clarify: ng-bind-html is a service in the module ngSanitize, which isn't included in the angularJS core. ng-bind-html-unsafe is part of the core ng module, but it includes the string you supply it without sanitizing it (see the example in the ngBindHtmlUnsafe docs).

If you want/need to use ngBindHtml, you need to include ngSanitize - available here

Upvotes: 27

Related Questions