angularJS如何忽略某些HTML标记?

Raf*_*ith 8 html tags angularjs

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

错误:[$ sanitize:badparse]清理程序无法解析以下html块:<3

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

我希望他只被<a>标记和标记<br />

那可能吗?

谢谢!

Goo*_*off 11

您可以创建过滤器来清理您的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 : '';
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

控制器:

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>'));
  });
}]);
Run Code Online (Sandbox Code Playgroud)

视图:

<div ng-bind-html="sanitized"></div>
Run Code Online (Sandbox Code Playgroud)

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


Ali*_*avi 7

我有同样的问题并通过使用修复它$sce.trustAsHtml,看到这个

$scope.body = $sce.trustAsHtml(htmlBody);

// In html
<div ng-bind-html="body">body</div>
Run Code Online (Sandbox Code Playgroud)

它解决了这个问题