如何在绑定到使用 ngBindHtml 查看时缩短 html 字符串的内容文本

how to shorten content text of html string while binding to view with ngBindHtml

我正在绑定 html 字符串以使用 ngBindHtml 查看。字符串内容是纯文本以及锚元素。
对于带有 ngBind 的纯文本,我可以使用 this 之类的过滤器将文本长度限制为特定的字数。

我已经通过在文档上创建一个临时元素并遍历它的子节点并计算 textContent 的长度来尝试它:

app.filter('sliceTextContent', function () {
  return function (str, max) {
    var counter = 0;
    var shortenedStr = '';
    var wrap = document.createElement('div');
    wrap.innerHTML = str;

    for (var i = 0; i < wrap.childNodes.length; i++) {

      if (wrap.childNodes[i].textContent.length + counter < max) {
        shortenedStr += (wrap.childNodes[i].innerHTML) ? wrap.childNodes[i].innerHTML : wrap.childNodes[i].textContent;
        counter += wrap.childNodes[i].textContent.length;
      } else {
        wrap.childNodes[i].textContent = wrap.childNodes[i].textContent.substr(0, max - counter);
        shortenedStr += (wrap.childNodes[i].innerHTML) ? wrap.childNodes[i].innerHTML : wrap.childNodes[i].textContent;
        break;
      }
    };
    return shortenedStr;
  }
});


我认为这不是最佳的,并且在遇到我数据库中的长字符串时可能会导致计时问题。 您有改进的想法吗

这是我会做的: 它的性能更高,因为:

  • 不需要虚拟 dom
  • 无需遍历整个字符串(只需遍历到最大值)。

假设:

  • 锚标签是:“”关闭。那应该是 有效 html 的情况。
  • Link 文本加起来未达到最大值

代码:

var longString = "Lorem ipsum dolor <a href='#'>link 1 </a> sit amet, consectetur adipiscing elit. Duis in rhoncus nisi. Suspendisse elementum convallis <a href='#'>link 1 </a>  faucibus. Nam elit nisl, cursus a mauris sit amet, mattis volutpat nulla. Suspendisse fermentum urna in lobortis semper. Vivamus eu commodo diam, ut blandit justo. Etiam at venenatis purus, a lobortis nisl. Ut fringilla mi nibh, id congue est ultricies ut. In maximus vestibulum sodales. Nulla tempor diam bibendum sapien tempus facilisis. Praesent suscipit dolor sed fringilla vulputate. Nulla dapibus est vitae magna sagittis sodales. In finibus semper convallis.";



function Filter (str, max) {
     
    if (str.length <= max) return str;
    
    var i = 0;
    var counter = 0;
    var insideAnchor = false;
    
    while (i < str.length && counter < max){
        
        i++;
        if (str[i] === '<' && str[i+1] === 'a')insideAnchor = true;
        if (insideAnchor && str[i] === '>' && str[i-1] ==='a' && str[i-2] === '/')insideAnchor = false;

        if (insideAnchor === false)counter ++;       
    }
    return str.substring(0,i);   
}

document.getElementById("me").innerHTML = '>>>' + Filter(longString, 21) + '<<<';
<p id="me"></p>