angularJS How can I ignore certain HTML tags?

前端 未结 3 1788
暖寄归人
暖寄归人 2020-12-31 19:01

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

Error: [$sanitize:badparse] The sanitizer was unable to parse the foll

相关标签:
3条回答
  • 2020-12-31 19:37

    To preserve existing ng-bind-html behaviour without crashing you can catch the $sanitize:badparse exception.

    The ngBindHtml component internally uses the ngSanitize service. Inject $sanitize into your controller and catch it.

    The advantage of this versus the $sce.trustAsHtml methods is that $sanitize does not introduce any potential security holes (eg. javascript injection).

    Controller (inject $sanitize):

    $scope.clean = function (string) {
        $scope.clean = function(string) {
            try {
                return $sanitize(string);
            } catch(e) {
                return;
            }
        };
    };
    

    This method could be improved with a cache of the last known good value.

    View:

    <div ng-bind-html="clean(body)"></div>
    
    0 讨论(0)
  • 2020-12-31 19:40

    I had the same problem and fixed it by using $sce.trustAsHtml, see this

    $scope.body = $sce.trustAsHtml(htmlBody);
    
    // In html
    <div ng-bind-html="body">body</div>
    

    It fix the issue

    0 讨论(0)
  • 2020-12-31 19:51

    You can create filter which will sanitize your html.

    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]*)\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 : '';
            });
        }
    });
    

    controller:

    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>'));
      });
    }]);
    

    view:

    <div ng-bind-html="sanitized"></div>
    

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

    0 讨论(0)
提交回复
热议问题