angularJS如何忽略某些HTML标记?
我得到这个错误是因为一个用户在他的帖子中添加了一个过滤器,你可以创建过滤器来清理你的html 我在it中使用了strip_标签功能angularJS如何忽略某些HTML标记?,html,angularjs,tags,Html,Angularjs,Tags,我得到这个错误是因为一个用户在他的帖子中添加了一个过滤器,你可以创建过滤器来清理你的html 我在it中使用了strip_标签功能 angular.module('filters',[]).factory('truncate',function(){ 返回功能条标签(输入,允许){ 允许=((允许的| |“”)+“”) .toLowerCase() .match(//g)| |[]) .join(“”);//确保允许的参数是一个仅包含小写标记的字符串(我遇到了相同的问题,并使用$sce.tru
angular.module('filters',[]).factory('truncate',function(){
返回功能条标签(输入,允许){
允许=((允许的| |“”)+“”)
.toLowerCase()
.match(//g)| |[])
.join(“”);//确保允许的参数是一个仅包含小写标记的字符串(我遇到了相同的问题,并使用$sce.trustAsHtml
修复了它,请参见此
$scope.body = $sce.trustAsHtml(htmlBody);
// In html
<div ng-bind-html="body">body</div>
$scope.body=$sce.trustAsHtml(htmlBody);
//在html中
身体
它修复了问题以保留现有的ng bind html
行为而不会崩溃。您可以捕获$sanitize:badparse
异常
ngBindHtml
在内部使用ngSanitize
。将$sanitize
注入控制器并捕获它
与$sce.trustAsHtml
方法相比,这种方法的优点是$sanitize
不会引入任何潜在的安全漏洞(例如javascript注入)
控制器(注入$sanitize
):
使用最后一个已知良好值的缓存可以改进此方法
视图:
I是否可以不替换错误的标记而显示它们?例如,在您的plunker中,不使用标记,只显示粗体的已清除标记?我认为这是一个坏主意。然后您将绕过ngSanitize安全检查。因此,您可能会打开应用程序以遭受HTML注入攻击。看,我没有使用ng bind HTML unsafe
which已被清除,如果没有ngSanitize
,则无法使用ng bind html
。因此不存在安全问题。
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>
$scope.body = $sce.trustAsHtml(htmlBody);
// In html
<div ng-bind-html="body">body</div>
$scope.clean = function (string) {
$scope.clean = function(string) {
try {
return $sanitize(string);
} catch(e) {
return;
}
};
};
<div ng-bind-html="clean(body)"></div>