angularjs - $sce.trustAsHtml 与 ng-bind-html

标签 angularjs

为什么我不能这样做:

<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/

相关文章:

javascript - 我应该如何在 AngularJS 中制作可配置模块

angularjs - 使用 AngularJS 通过自定义登录进行 Spring Security 身份验证

javascript - 基于 Controller 返回值的 Ng 类

javascript - 使用 ng-click 过滤新闻和事件

angularjs - 测试使用另一个使用 $http 的服务的 angular.service

javascript - AngularJS 教程不绑定(bind)数据

javascript - 如何从Angularjs中的下拉列表中获取选定的值?

jquery - Angular js : camera slideshow jquery plugin is not working in partial view

javascript - Cakephp 2.5 : add control on js, css,图像使用蛋糕 Controller

angularjs - 如何使用一个文件中定义的所有 View 创建 AngularJS 应用程序?