【问题标题】:Toggle ng-bind-html切换 ng-bind-html
【发布时间】:2024-01-22 18:19:01
【问题描述】:

我的作用域中有一个字符串,但我并不总是知道是否要转义 HTML。本质上,我有一个布尔值,它会说明是否应该转义 HTML。

代码

这是我的一些示例代码:

$scope.result = "<b>foo</b>bar";
$scope.html = false; // In this case the HTML *would* be escaped

这是一个插入 HTML 的情况,如 innerHTML:

$scope.result = "<strike>foo</strike>bar";
$scope.html = true; // The HTML would be escaped

我尝试过的其他解决方案

我不确定 “Angular 方式” 会是什么,虽然我曾想过使用 .removeAttribute 进行黑客攻击,但我觉得这非常 hacky,必须有更好的方法。

【问题讨论】:

  • 为什么不使用一个指令来传递一个指示 HTML 是否被转义的属性?像这样

标签: javascript html angularjs ng-bind-html ng-bind


【解决方案1】:

一个例子是这样的:

<p ng-bind-html-unsafe="data.markupData"></p>

使用 ng-repeat 进行迭代也很简单:

<div ng-repeat="item in items">
  <p ng-bind-html-unsafe="item.markupData"></p>
</div>

1。创建一个新的控制器

var ExampleCtrl = function($scope) {
}

在您的 HTML 中:

<div ng-repeat="example in Examples" ng-controller="ExampleCtrl">
  <p ng-bind-html="trustedExample"></p>

<hr />

</div>

2。将 Strict Contextual Escaping 服务添加到您的控制器

var ExampleCtrl = function($scope, $sce) {

}

3。对数据使用 $sce.trustAsHtml 函数

var ExampleCtrl = function($scope, $sce) {
  $scope.trustedExample = $sce.trustAsHtml($scope.example);
}

我希望这会有所帮助

【讨论】:

  • 那么基于布尔范围变量,我将如何在bind-html-unsafebind-html 之间切换?
【解决方案2】:

这样做的一种“角度”方式是编写一个filter,它接受 html 和布尔值并返回转义/未转义的 html。

这里有一个关于如何编写 dngular 过滤器的基本教程:https://docs.angularjs.org/tutorial/step_09

关于如何打开 html,请尝试使用 $sanitizehttps://docs.angularjs.org/api/ngSanitize/service/$sanitize

【讨论】: