$ sce.trustAsHtml与ng-bind-html

Fra*_*isc 14 angularjs

为什么我不能这样做:

<div>{{data | htmlfilterexample}}</div>
Run Code Online (Sandbox Code Playgroud)

当我在过滤器内部返回时:

return $sce.trustAsHtml(input);
Run Code Online (Sandbox Code Playgroud)

<div ng-bind-html="data | htmlfilterexample"></div>无论过滤器返回input还是使用,都可以使用$sce.trustAsHtml(input).

我的印象是$sce使得HTML值得信任,并且ng-bind-html该方法返回的输出不需要.

谢谢.

Kay*_*ave 34

$sce.trustAsHtml()生成一个可以安全使用的字符串ng-bind-html.如果你不在字符串上使用该函数,那么ng-bind-html会产生错误:[ $sce:unsafe] Attempting to use an unsafe value in a safe context. 所以$ sce没有摆脱ng-bind-html它的需要,而是使它使用它的进程安全的字符串.

你遇到的具体问题在于ng-bind和之间的区别ng-bind-html

使用{{}}相当于ng-bind.所以,看一下ng-bind源代码(ng-bind-*源代码),我们看到它使用了这个:

element.text(value == undefined ? '' : value);
Run Code Online (Sandbox Code Playgroud)

同时ng-bind-html,除其他事项外,执行以下操作:

var parsed = $parse(attr.ngBindHtml);
element.html($sce.getTrustedHtml(parsed(scope)) || '');
Run Code Online (Sandbox Code Playgroud)

关键的一点是,ng-bind使用.text(http://api.jquery.com/text/)会导致显示字符串的文本表示(忽略它是否值得信赖).

虽然ng-bind-html使用的.html(http://api.jquery.com/html/)导致HTML解释的版本(如果宣布为安全的getTrustedHtml())

  • 说"$ sce.trustAsHtml()产生一个可以安全地与ng-bind-html一起使用的字符串"似乎具有灾难性的误导和错误.它产生了*sanitisation bypass*的代理,结果可能完全*不安全*与ng-bind-html一起使用.通常,如果与ng-bind-html一起使用的表达式被评估为"X <script> alert('foo')</ script> X`,那么脚本元素将被`$ sanitize`删除,留下`XX`,但是如果值是通过trustAsHtml派生的,脚本标签将保留.这是它的目的,可以在需要时注入任意HTML,但它并没有使任何"安全". (6认同)