我遇到了这个错误,因为其中一个用户在他的帖子中添加了<3
错误:[$sanitize:badparse] 清理程序无法解析以下 HTML 代码块:<3
我编写了代码:ng-bind-html="Detail.details"
我只想保留<a>
标签和<br />
标签
这可能吗?
谢谢!
你可以创建过滤器来清理你的HTML。
我在其中使用了strip_tags函数(http://phpjs.org/functions/strip_tags/)
angular.module('filters', []).factory('truncate', function () {
return function strip_tags(input, allowed) {
allowed = (((allowed || '') + '')
.toLowerCase()
.match(/<[a-z][a-z0-9]*>/g) || [])
.join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '')
.replace(tags, function($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
}
});
控制器:
angular.module('myApp', ['filters'])
.controller('IndexController', ['$scope', 'truncate', '$sce', function($scope, truncate, $sce){
$scope.text="";
$scope.$watch('text', function(){
$scope.sanitized = $sce.trustAsHtml(truncate($scope.text, '<a><br>'));
});
}]);
视图:
<div ng-bind-html="sanitized"></div>
我曾经遇到过同样的问题,通过使用$sce.trustAsHtml
进行修复,查看此链接。
$scope.body = $sce.trustAsHtml(htmlBody);
// In html
<div ng-bind-html="body">body</div>
它修复了问题。
ng-bind-html-unsafe
,你不能在没有ngSanitize
的情况下使用ng-bind-html
。所以没有安全问题。 - Ali Adraving-bind-html
行为而不崩溃,您可以捕获$sanitize:badparse
异常。
ngBindHtml
组件在内部使用ngSanitize
服务。将$sanitize
注入您的控制器并进行捕获。$sce.trustAsHtml
方法相比,这种方法的优点是$sanitize
不会引入任何潜在的安全漏洞(例如javascript注入)。$sanitize
):$scope.clean = function (string) {
$scope.clean = function(string) {
try {
return $sanitize(string);
} catch(e) {
return;
}
};
};
<div ng-bind-html="clean(body)"></div>