как санировать не нашел img с $ sce angularJS 1.6 - PullRequest
0 голосов
/ 06 апреля 2020

Я получаю html код из службы API и связываю его с div, используя ng-bind- html, но иногда я получаю изображения, подобные этому http://t1.gstatic.com/images?q=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, которого не существует, и я хочу убери это. Итак, я использовал функцию $ sce.trustAs Html, чтобы удалить ее, но она не работала.

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

в моем контроллере

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

Заранее спасибо

1 Ответ

2 голосов
/ 10 апреля 2020

Проверьте мое решение вашей проблемы:

<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);
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...