Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$sce.trustAsHtml vs. ng-bind-html

Tags:

angularjs

Why can't I do this:

<div>{{data | htmlfilterexample}}</div>

When, inside the filter, I am returning:

return $sce.trustAsHtml(input);

Using <div ng-bind-html="data | htmlfilterexample"></div> works regardless if the filter returns input or $sce.trustAsHtml(input).

I was under the impression that $sce makes HTML trustworth and ng-bind-html isn't needed for output returned by that method.

Thanks.

like image 556
Francisc Avatar asked Nov 26 '13 15:11

Francisc


People also ask

What is SCE trustAsHtml?

The ng-controller uses $sce (Strict Contextual Escaping) service which is used to mark the HTML as trusted using the trustAsHtml method. Note: Unless the HTML content is trusted using the $sce service, it will not be displayed using ng-bind-html directive.

What is Ng-bind HTML in AngularJS?

The ng-bind-html directive is a secure way of binding content to an HTML element. When you are letting AngularJS write HTML in your application, you should check the HTML for dangerous code. By including the "angular-sanitize.

What is $SCE angular?

Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.

What is Ng-bind used for?

The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable, or expression, changes, the content of the specified HTML element will be changed as well.


1 Answers

$sce.trustAsHtml() produces a string that is safe to use with ng-bind-html. Were you to not use that function on the string then ng-bind-html would yield the error: [$sce:unsafe] Attempting to use an unsafe value in a safe context. So $sce doesn't get rid of the need for ng-bind-html rather it makes the string it processes safe to use with it.

The specific issue you're running into lies in the difference between ng-bind and ng-bind-html

Using {{}} is the equivalent of ng-bind. So, looking at the ng-bind source code (ng-bind-* source code) we see that it uses this:

element.text(value == undefined ? '' : value);

while ng-bind-html, amongst other things, does the following:

var parsed = $parse(attr.ngBindHtml);
element.html($sce.getTrustedHtml(parsed(scope)) || '');

The key takeaway being that the ng-bind use of .text (http://api.jquery.com/text/) results in the text representation of the string being displayed (ignoring whether it's HTML trustworthy).

While the ng-bind-html use of .html (http://api.jquery.com/html/) results in the html interpreted version (if declared safe by getTrustedHtml())

like image 74
KayakDave Avatar answered Sep 17 '22 19:09

KayakDave