Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding HTML in an Angular expression

Tags:

angularjs

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>
like image 386
Terry Avatar asked Apr 11 '13 15:04

Terry


People also ask

How do you write expressions in angular HTML?

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.

How do you write an expression in HTML?

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.

What are expressions in angular 2?

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.


1 Answers

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

like image 77
Tiago Roldão Avatar answered Oct 28 '22 01:10

Tiago Roldão