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.
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.
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.
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.
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.
$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()
)
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