angularJS如何忽略某些HTML标记?

前端之家收集整理的这篇文章主要介绍了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/

  1. angular.module('filters',[]).factory('truncate',function () {
  2. return function strip_tags(input,allowed) {
  3. allowed = (((allowed || '') + '')
  4. .toLowerCase()
  5. .match(/<[a-z][a-z0-9]*>/g) || [])
  6. .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
  7. var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,commentsAndPHPTags = /<!--[\s\S]*?-->|<\?(?:PHP)?[\s\S]*?\?>/gi;
  8. return input.replace(commentsAndPHPTags,'')
  9. .replace(tags,function($0,$1) {
  10. return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
  11. });
  12. }
  13. });

控制器:

  1. angular.module('myApp',['filters'])
  2. .controller('IndexController',['$scope','truncate','$sce',function($scope,truncate,$sce){
  3. $scope.text="";
  4.  
  5. $scope.$watch('text',function(){
  6. $scope.sanitized = $sce.trustAsHtml(truncate($scope.text,'<a><br>'));
  7. });
  8. }]);

视图:

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

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

猜你在找的Angularjs相关文章