Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 that ng-bind-html ="Detail.details"

I want him to be taken only <a> tag and tag <br />

Is that possible?

Thank you!

like image 749
Mr.Smith Avatar asked Mar 20 '14 12:03

Mr.Smith


People also ask

How do I ignore HTML tags?

If you have a certain part or section of an HTML or XHTML document that you want CSE HTML Validator to ignore, then you can enclose it in "cseignore" tags.

How can we hide or remove tags in angular?

The ngHide directive shows or hides the given HTML element based on the expression provided to the ngHide attribute. The element is shown or hidden by removing or adding the . ng-hide CSS class onto the element.

How do I ignore a div in HTML?

You cannot do such things in HTML. You can use JavaScript to modify the document tree, replacing element nodes by their contents or by manipulating the innerHTML property. Of course, search engines and friends would still “see” the tags you make browsers ignore.


1 Answers

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

like image 186
Goodnickoff Avatar answered Oct 05 '22 01:10

Goodnickoff