angularJS 如何忽略某些 HTML 标签?

2022-01-18 00:00:00 tags angularjs html

我收到此错误是因为其中一位用户在他的帖子中添加了 <3

I got this error because one of the users added in his post <3

错误:[$sanitize:badparse] sanitizer 无法解析以下 html 块:<3

Error: [$sanitize:badparse] The sanitizer was unable to parse the following block of html: <3

我写的代码 ng-bind-html ="Detail.details"

我要他只取<a>标签和<br/>

这可能吗?

谢谢!

推荐答案

您可以创建过滤器来清理您的 html.

You can create filter which will sanitize your html.

我在其中使用了 strip_tags 函数http://phpjs.org/functions/strip_tags/

I used in it strip_tags function 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]*)[^>]*>/gi,
        commentsAndPhpTags = /<!--[sS]*?-->|<?(?:php)?[sS]*??>/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

相关文章