【问题标题】:how to sanitize not found img with $sce angularJS 1.6如何使用 $sce angularJS 1.6 清理未找到的 img
【发布时间】:2020-04-06 16:29:45
【问题描述】:

我从 API 服务获取 html 代码并使用 ng-bind-html 将其绑定到 div,但有时我会得到像 http://t1.gstatic.com/images?q=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 这样不存在的图像,我想将其删除。因此,我使用 $sce.trustAsHtml 函数将其删除,但它不起作用。

<div ng-repeat="output in data">
<p ng-bing-html=$ctrl.getHtml(output)></p>
</div>

在我的控制器中

function _getHtml(output)
{
   return $sce.trustAsHtml(output);
}

提前致谢

【问题讨论】:

  • 您能否发布一个数据示例,一般可以包含哪些类型的数据?
  • @Mostav "


    t1.gstatic.com/… face="Tahoma" >

    戴娜

标签: angularjs


【解决方案1】:

查看我的解决方案以解决您的问题:

<div ng-repeat="output in data">
     <p ng-bing-html="getOutputElement(output)"></p>
</div>

getOutputElement 定义如下:

$scope.getOutputElement = function (output) {
   var ele = document.createElement('div');
   ele.innerHTML = output;
   var imgName = ele.getElementsByTagName('img')[0];
   // If img found, then check with an http GET status code comparison with 200
   if (imgName) {
       var imgValue = imgName.getAttribute("src");
       var request = new XMLHttpRequest();
       request.open('GET', imgValue, false);
       request.send(null);

       if (request.status === 200) {
           // html string with img ele and url is valid -> return the string
           return $sce.trustAsHtml(output);
       }
       // html string with img ele but img url not valid -> return what you want
       // for example you can remove img element and keep other html then return string without img
       imgName.remove();
       return $sce.trustAsHtml(ele.innerHTML);
   }
   // html string without img ele
   return $sce.trustAsHtml(output);
};

【讨论】:

  • 刚刚添加了一个更新,以便在图像无效的情况下从ele中删除img。
  • 我必须使用 $sce 或 $sanitize。
  • 再次检查,更新我的帖子,它在 cmets 中有
  • 谢谢,但它仍然不是我想要的。我必须删除带有 $sce 及其属性的图像。
  • img 是受信任的元素,您如何使用 $sce 将其删除?无论如何,函数 $scope.getOutputElement 的返回值将是 $sce.trustAsHtml 的结果,并且没有无效图像。能否请您提供更多详细信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-05
  • 2017-10-08
  • 2014-01-03
  • 2018-10-27
  • 1970-01-01
  • 2012-05-31
相关资源
最近更新 更多