javascript AngularJS 使用 $sce.trustAsHtml 和 ng-repeat
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24459194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS using $sce.trustAsHtml with ng-repeat
提问by ZoM
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.
我正在尝试将 $sce.trustAsHtml() 与 ng-repeat 中的对象的属性一起使用。结果是 HTML 完全空白。尽管使用 ngSanitize 可以正确输出 HTML。
<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.
顺便说一下,我正在使用 AngularJS v1.3.0-beta.3。不确定是否有错误或我做错了什么。
回答by gkalpak
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
.
您不能$sce.trustAsHtml
在表达式中使用(除非$sce
是 上的属性$scope
),因为表达式是在$scope
.
The cleanest approach is to use ngSanitize
.
The second cleanest is to expose $sce.trustAsHtml
as a function in the $scope
:
最干净的方法是使用ngSanitize
.
第二个最干净的方法是$sce.trustAsHtml
作为一个函数公开$scope
:
<div ng-repeat="...">
<p ng-bind-html="trustAsHtml(question.body)"></p>
</div>
$scope.trustAsHtml = $sce.trustAsHtml;
回答by Moin Haidar
OR have a filter:
或者有一个过滤器:
angular.module('myApp')
.filter("sanitize", ['$sce', function($sce) {
return function(htmlCode){
return $sce.trustAsHtml(htmlCode);
}
}]);
in html:
在 html 中:
<div ng-bind-html="question.body | sanitize"></div>