微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angularJS如何忽略某些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.

我在其中使用了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

原文地址:https://www.jb51.cc/angularjs/142509.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐