gpt4 book ai didi

javascript - 切换 ng-bind-html

转载 作者:行者123 更新时间:2023-12-03 08:01:29 25 4
gpt4 key购买 nike

我的作用域中有一个字符串,但我并不总是知道是否要转义 HTML。本质上我有一个 bool 值,它会说明 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 Way”是什么,虽然我考虑过使用.removeAttribute进行黑客攻击,但我发现这个>非常老套,必须有更好的方法。

最佳答案

An example went something like:

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

Iteration with ng-repeat was also straightforward:

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

1。创建一个新的 Controller

var ExampleCtrl = function($scope) {
}

在你的 HTML 中:

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

<hr />

</div>

2。将严格上下文转义服务添加到您的 Controller

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

}

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

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

我希望这会有所帮助

关于javascript - 切换 ng-bind-html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34562609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com