Skip to content Skip to sidebar Skip to footer

AngularJS How Can I Ignore Certain HTML Tags?

I got this error because one of the users added in his post <3 Error: [$sanitize:badparse] The sanitizer was unable to parse the following block of html: <3 I wrote code t

Solution 1:

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


Solution 2:

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


Solution 3:

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>

Post a Comment for "AngularJS How Can I Ignore Certain HTML Tags?"