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>
AngularJS expressions can be written inside double braces: {{ expression }} . AngularJS expressions can also be written inside a directive: ng-bind="expression" . AngularJS will resolve the expression, and return the result exactly where the expression is written.
Expressions are used to bind application data to HTML. Expressions are written inside double curly braces such as in {{ expression}}. Expressions behave similar to ngbind directives. AngularJS expressions are pure JavaScript expressions and output the data where they are used.
One of the first things a developer writes in Angular, other than the ng-app directive, is an expression. This is easily identified as the code written inside of a binding {{ }} or directive.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With