为什么我不能这样做:
<div>{{data | htmlfilterexample}}</div>
当我在过滤器内返回时:
return $sce.trustAsHtml(input);
使用
<div ng-bind-html="data | htmlfilterexample"></div>
无论过滤器是否返回 input
都有效或 $sce.trustAsHtml(input)
.我的印象是
$sce
使 HTML 值得信赖和 ng-bind-html
该方法返回的输出不需要。谢谢。
最佳答案
$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-* source code )我们看到它使用了这个:
element.text(value == undefined ? '' : value);
而
ng-bind-html
,除其他外,执行以下操作:var parsed = $parse(attr.ngBindHtml);
element.html($sce.getTrustedHtml(parsed(scope)) || '');
关键要点是
ng-bind
使用 .text ( http://api.jquery.com/text/ ) 导致显示字符串的文本表示(忽略它是否是 HTML 可信的)。而
ng-bind-html
使用 .html ( http://api.jquery.com/html/ ) 结果是 html 解释版本 (如果 getTrustedHtml()
声明安全)
关于angularjs - $sce.trustAsHtml 与 ng-bind-html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20221711/