我正在尝试在ng-repeat中使用$sce.trustAsHtml()处理对象属性,但结果是HTML完全为空。不过,使用ngSanitize可以正确输出HTML。
<div ng-repeat="question in questions">
<p ng-bind-html="$sce.trustAsHtml(question.body)">
</p>
</div>
顺便说一下,我正在使用AngularJS v1.3.0-beta.3。不确定是程序有问题还是我的操作有误。
我正在尝试在ng-repeat中使用$sce.trustAsHtml()处理对象属性,但结果是HTML完全为空。不过,使用ngSanitize可以正确输出HTML。
<div ng-repeat="question in questions">
<p ng-bind-html="$sce.trustAsHtml(question.body)">
</p>
</div>
顺便说一下,我正在使用AngularJS v1.3.0-beta.3。不确定是程序有问题还是我的操作有误。
在表达式中(除非 $sce
是 $scope
上的属性),否则您不能使用$sce.trustAsHtml
,因为表达式是在$scope
的上下文中计算的。
最清晰的方法是使用ngSanitize
。
第二种最清晰的方法是将$sce.trustAsHtml
公开为$scope
中的函数:
<div ng-repeat="...">
<p ng-bind-html="trustAsHtml(question.body)"></p>
</div>
$scope.trustAsHtml = $sce.trustAsHtml;
或者使用过滤器:
angular.module('myApp')
.filter("sanitize", ['$sce', function($sce) {
return function(htmlCode){
return $sce.trustAsHtml(htmlCode);
}
}]);
在HTML中:
<div ng-bind-html="question.body | sanitize"></div>
$sce.trustAsHtml(questions)
并仅使用<p ng-bind-html="question.body"></p>
如何? - Hardik Mishra