AngularJS 使用 $sce.trustAsHtml 和 ng-repeat [英] AngularJS using $sce.trustAsHtml with ng-repeat

查看:25
本文介绍了AngularJS 使用 $sce.trustAsHtml 和 ng-repeat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 $sce.trustAsHtml() 与 ng-repeat 中的对象的属性一起使用.结果是 HTML 完全空白.HTML 使用 ngSanitize 正确输出.

<p ng-bind-html="$sce.trustAsHtml(question.body)"></p>

顺便说一下,我使用的是 AngularJS v1.3.0-beta.3.不确定是否有错误或我做错了什么.

解决方案

你不能在表达式中使用 $sce.trustAsHtml(除非 $sce 是一个属性在 $scope) 上,因为表达式是在 $scope 的上下文中计算的.

最干净的方法是使用 ngSanitize.
第二个最干净的方法是将 $sce.trustAsHtml 作为 $scope 中的函数公开:

<p ng-bind-html="trustAsHtml(question.body)"></p>

$scope.trustAsHtml = $sce.trustAsHtml;

I'm trying to use $sce.trustAsHtml() with a property of an object in ng-repeat. The result is that the HTML is totally blank. The HTML outputs correctly using ngSanitize though.

<div ng-repeat="question in questions">
    <p ng-bind-html="$sce.trustAsHtml(question.body)">
    </p>
</div>

I'm on AngularJS v1.3.0-beta.3 by the way. Not sure if there's a bug or I do something wrong.

解决方案

You can't use $sce.trustAsHtml in an expression (unless $sce is a property on the $scope) because expressions are evaluated in the context of the $scope.

The cleanest approach is to use ngSanitize.
The second cleanest is to expose $sce.trustAsHtml as a function in the $scope:

<div ng-repeat="...">
    <p ng-bind-html="trustAsHtml(question.body)"></p>
</div>

$scope.trustAsHtml = $sce.trustAsHtml;

这篇关于AngularJS 使用 $sce.trustAsHtml 和 ng-repeat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆