Angularjs ng-bind-html с пользовательским фильтром

В настоящее время я работаю с ng-bind-html. По сути, то, что я пытаюсь сделать, это когда я публикую блог, блог содержит ссылки и другие стили. Поэтому, когда я пытаюсь показать список блогов, я использую ng-bing-html следующим образом:

<p ng-bind-html="blog.blogContent"></p>

который отлично работает.

Но, кроме того, я пытаюсь обрезать блог и показывать только несколько абзацев с опцией «Просмотреть больше», передавая пользовательский фильтр. Но когда я прохожу фильтр, я получаю следующее:

<p ng-bind-html="blog.blogContent | Truncate"></p>

Error: [$sanitize:badparse] The sanitizer was unable to parse the
following block of html: <a href="https:.......

Мой фильтр выглядит так:

return function (text, length, end) {
    if (text !== undefined) {
      if (isNaN(length)) {
        length = 450;
      }

      if (end === undefined) {
        end = ".......";
      }

      if (text.length <= length || text.length - end.length <= length) {
        return text;
      } else {
        return String(text).substring(0, length - end.length) + end;
      }
    }

person Rana_S    schedule 11.09.2015    source источник
comment
Робинсон. Похоже, ваш фильтр запускается первым и обрезает HTML. затем ng-bind-html пытается проанализировать недопустимую строку HTML, что приводит к ошибке.   -  person    schedule 11.09.2015
comment
Вы можете изменить свой фильтр, чтобы использовать код, опубликованный Minouris в этом решении, и посмотреть, поможет ли это. stackoverflow.com/questions/3822233/   -  person    schedule 11.09.2015
comment
Спасибо, я @user1!   -  person Rana_S    schedule 11.09.2015


Ответы (2)


Вы можете решить эту проблему, используя пользовательские директивы и фильтры. попробуйте этот: https://stackoverflow.com/a/45076560/6816707

person Uttam Rahane    schedule 13.07.2017

Я использовал решение, опубликованное Минурисом в этом посте (Javascript обрезать HTML-текст), и адаптировал его к фильтр AngularJS. Кажется, это работает очень хорошо. Фильтр

angular.module('plunker').filter('Truncate', function() {
  return function(text, length, end) {
       if (text !== undefined) {
      if (isNaN(length)) {
        length = 20;
      }

      if (end === undefined) {
        end = ".......";
      }

      if (text.length <= length || text.length - end.length <= length) {
        return text;
      }

    var truncated = text.substring(0, length);
    // Remove line breaks and surrounding whitespace
    truncated = truncated.replace(/(\r\n|\n|\r)/gm,"").trim();
    // If the text ends with an incomplete start tag, trim it off
    truncated = truncated.replace(/<(\w*)(?:(?:\s\w+(?:={0,1}(["']{0,1})\w*\2{0,1})))*$/g, '');
    // If the text ends with a truncated end tag, fix it.
    var truncatedEndTagExpr = /<\/((?:\w*))$/g;
    var truncatedEndTagMatch = truncatedEndTagExpr.exec(truncated);
    if (truncatedEndTagMatch != null) {
        var truncatedEndTag = truncatedEndTagMatch[1];
        // Check to see if there's an identifiable tag in the end tag
        if (truncatedEndTag.length > 0) {
            // If so, find the start tag, and close it
            var startTagExpr = new RegExp(
                "<(" + truncatedEndTag + "\\w?)(?:(?:\\s\\w+(?:=([\"\'])\\w*\\2)))*>");
            var testString = truncated;
            var startTagMatch = startTagExpr.exec(testString);

            var startTag = null;
            while (startTagMatch != null) {
                startTag = startTagMatch[1];
                testString = testString.replace(startTagExpr, '');
                startTagMatch = startTagExpr.exec(testString);
            }
            if (startTag != null) {
                truncated = truncated.replace(truncatedEndTagExpr, '</' + startTag + '>');
            }
        } else {
            // Otherwise, cull off the broken end tag
            truncated = truncated.replace(truncatedEndTagExpr, '');
        }
    }
    // Now the tricky part. Reverse the text, and look for opening tags. For each opening tag,
    //  check to see that he closing tag before it is for that tag. If not, append a closing tag.
    var testString = reverseHtml(truncated);
    var reverseTagOpenExpr = /<(?:(["'])\w*\1=\w+ )*(\w*)>/;
    var tagMatch = reverseTagOpenExpr.exec(testString);
    while (tagMatch != null) {
        var tag = tagMatch[0];
        var tagName = tagMatch[2];
        var startPos = tagMatch.index;
        var endPos = startPos + tag.length;
        var fragment = testString.substring(0, endPos);
        // Test to see if an end tag is found in the fragment. If not, append one to the end
        //  of the truncated HTML, thus closing the last unclosed tag
        if (!new RegExp("<" + tagName + "\/>").test(fragment)) {
            truncated += '</' + reverseHtml(tagName) + '>';
        }
        // Get rid of the already tested fragment
        testString = testString.replace(fragment, '');
        // Get another tag to test
        tagMatch = reverseTagOpenExpr.exec(testString);
    }
    return truncated;
  }
  }

  function reverseHtml(str) {
    var ph = String.fromCharCode(206);
    var result = str.split('').reverse().join('');
    while (result.indexOf('<') > -1) {
        result = result.replace('<',ph);
    }
    while (result.indexOf('>') > -1) {
        result = result.replace('>', '<');
    }
    while (result.indexOf(ph) > -1) {
        result = result.replace(ph, '>');
    }
    return result;
}
  });

Рабочий проект: http://plnkr.co/edit/oCwmGyBXB26omocT2q9m?p=preview

Я не тестировал вышеуказанное решение, и вы можете столкнуться с проблемами с более сложными строками HTML. Могу ли я предложить использовать библиотеку Jquery, например https://github.com/pathable/truncate, чтобы быть в безопасности ?

person Community    schedule 11.09.2015