繁体   English   中英

切换ng-bind-html

[英]Toggle ng-bind-html

我的范围内有一个字符串,但我并不总是知道我是否要转义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

我尝试过的其他解决方案

我不确定执行此操作的“角度方法”是什么,并且尽管我想到了使用.removeAttribute进行黑客攻击,但我发现这 hacky,因此必须有更好的方法。

一个例子是这样的:

<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.将严格的上下文转义服务添加到您的控制器

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

}

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

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

我希望这个能帮上忙

一种“角度”处理方式是编写一个filter ,该filter接受html和boolean值并返回转义/未转义的html。

这是有关如何编写双色过滤器的基本教程: https ://docs.angularjs.org/tutorial/step_09

关于如何截取HTML,请尝试使用$sanitizehttps ://docs.angularjs.org/api/ngSanitize/service/ $ sanitize

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM