渲染带html结构的字符串,使用ng-bind-html可以实现。
ng-bind-html的坑:
ng-bind-html指令会在运行时过滤掉一些不安全的标签来防止xxs攻击,提高安全性。所以会导致字符串的某些标签如<button></button>,<input>等不显示。
解决方案:
1.在angularjs中默认是不相信添加的html内容,ng-bind-html指令是通过一个安全的方式将内容绑定到html元素上,该属性依赖于$sanitize,需要在项目中引入angular-sanitize.js文件,并在module定义时注入该服务ngSanitize。
2.在angularjs中绑定的数据有html标签时,会被认为是不安全的而自动过滤掉,为了保留这些标签就需要开启非安全模式,这是非常危险的。$sce是angularjs自带的安全处理模块,因此必须利用$sce.trustAsHtml,告知angularjs这是可信的html内容。否则你将会得到$sce:unsafe的异常错误。
第一种解决方案,该方案中需要展示的文本不包含\n换行。代码如下:
// html代码
<body ng-app="app">
<div ng-bind-html="content|to_trusted"></div>
</body>
// 控制器代码
var control = app.module('LogController', function($scope){
// 获取文本内容
$scope.content = '文本中的内容';
})
// js过滤器代码
var app = angular.module('app.filters',['ngSanitize'])
app.filter(
'to_trusted',
[
'$sce',function($sce) {
return function(text) {
return $sce.trustAsHtml(text)
}
}
]
)
第二种解决方案,当文本内容中包含\n换行字符串时。代码如下:
// html代码
<body ng-app="app">
<div ng-bind-html="content|to_trusted"></div>
</body>
// 控制器代码
var control = app.module('LogController', function($scope){
// 获取文本内容
let text = '文本中的内容';
// 当文本内容包含\n字符串,进一步处理下
$scope.content = text.replace(/\n/g,'<br />');
})
// js过滤器代码
var app = angular.module('app.filters',['ngSanitize'])
app.filter(
'to_trusted',
[
'$sce',function($sce) {
return function(text) {
return $sce.trustAsHtml(text)
}
}
]
)