1

我们正在使用 AngularJS 尝试将用户输入的内容显示为 HTML。大多数情况下,用户输入我们使用 ng-bind-html 正确显示的有效/安全数据。有时他们会输入无效的 HTML,我仍希望将其显示为原始文本。

如果我使用 ng-bind-html 尝试显示无效的 HTML,我会收到此错误:

[$sanitize:badparse] The sanitizer was unable to parse the following block of html:

我不想使用 trustAsHtml,因为我不信任我们的消毒剂,并希望确保我们不会在页面上显示不安全的 html。

4

2 回答 2

1

根据ngBindHtmlDirective你可以这样做:

HTML:

<div ng-if="isSafeHtml()">
  <div ng-bind-html="invalidHtml"></div>
</div>
<div ng-if="!isSafeHtml()">
  {{invalidHtml}}
</div> 

JS:

$scope.isSafeHtml = function() {
   return !!$sce.getTrustedHtml($scope.invalidHtml);
}

修改后的 plunkr:http ://plnkr.co/edit/Besix3PfQ1TjUEEagfca?p=preview

于 2015-06-04T18:02:34.370 回答
0

我最终创建了一个指令来执行此操作。这是它的使用方法。

<div ng-bind-html-if-safe="SomeHtml"></div>

指令的来源可以在这里找到。

于 2015-06-05T14:28:53.450 回答