AngularJS如何忽略某些HTML标签?

8

我遇到了这个错误,因为其中一个用户在他的帖子中添加了<3

错误:[$sanitize:badparse] 清理程序无法解析以下 HTML 代码块:<3

我编写了代码:ng-bind-html="Detail.details"

我只想保留<a>标签和<br />标签

这可能吗?

谢谢!


1
我喜欢这样的错误报告。 - kaiser
3个回答

10

你可以创建过滤器来清理你的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>

http://plnkr.co/edit/qOuvpSMvooC6jR0HxCNT?p=preview


有没有可能不替换错误的标签,而是将它们显示出来呢? 例如,在您的 Plunker 中,可以显示 <b>Bold sanitized</b>,而不是没有 <b> 标签。 - Guillaume Cisco

7

我曾经遇到过同样的问题,通过使用$sce.trustAsHtml进行修复,查看此链接。

$scope.body = $sce.trustAsHtml(htmlBody);

// In html
<div ng-bind-html="body">body</div>

它修复了问题。


1
我认为这是一个不好的想法。这样你就绕过了ngSanitize安全检查。因此,你可能会让你的应用程序受到HTML注入攻击的威胁。 - Carlos Morales
看,我没有使用已经弃用的ng-bind-html-unsafe,你不能在没有ngSanitize的情况下使用ng-bind-html。所以没有安全问题。 - Ali Adravi

3
为了保留现有的ng-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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接