$sce.trustAsHtml 与 ng-bind-html

2024-01-01

为什么我不能这样做:

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

当我在过滤器内返回时:

return $sce.trustAsHtml(input);

Using <div ng-bind-html="data | htmlfilterexample"></div>无论过滤器是否返回都有效input or $sce.trustAsHtml(input).

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

Thanks.


$sce.trustAsHtml()生成一个可以安全使用的字符串ng-bind-html。如果你不在字符串上使用该函数ng-bind-html会产生错误:[$sce:unsafe] Attempting to use an unsafe value in a safe context. So $sce 并没有消除对ng-bind-html相反,它使得它处理的字符串可以安全地使用。

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

Using {{}}相当于ng-bind。所以,看着ng-bind源代码 (ng-bind-* 源代码 https://github.com/angular/angular.js/blob/d7ed885984d58d344350ae267f51e8096bb6bea6/src/ng/directive/ngBind.js)我们看到它使用了这个:

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

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

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

关键要点是ng-bind use of .text (http://api.jquery.com/text/ http://api.jquery.com/text/) 导致显示字符串的文本表示形式(忽略它是否是 HTML 可信的)。

虽然ng-bind-html use of .html (http://api.jquery.com/html/ http://api.jquery.com/html/) 结果为 html 解释版本(如果宣布安全getTrustedHtml())

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

$sce.trustAsHtml 与 ng-bind-html 的相关文章