我正在绑定一个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;
}
});
我认为这不是最佳的,并且在遇到我在数据库中的长字符串时可能会导致时序问题。 你有改进它的想法吗?
答案 0 :(得分:1)
这是我要做的: 它的性能更高,因为:
假设:
代码:
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) + '<<<';
&#13;
<p id="me"></p>
&#13;