使用HTML标签AngularJS limitTo [英] AngularJS limitTo using HTML tags
问题描述
我在AngularJS一些绑定,我想限制显示的字符的长度。这是一个很简单的问题,当你只是一个简单的文本内容。
I have some bindings in AngularJS and I want to limit the length of characters displayed. It's a quite simple question when you have just a simple text content.
不过,我有一个包含HTML标签的文本:
However, I have text that contains HTML tags:
$scope.text = "<span><h1>Example</h1><p>Special Text</p></span>"
和也
$scope.maxNumberOfChar = 10;
当我使用下面的行它计算考虑到HTML标签的字符数。
When I use the following line it counts the number of chars taking into account HTML tags.
这可能是最好的解决方案来解决这个问题,只计算字符数,丢弃HTML标签?
Which could be the best solution to solve this problem and count only the number of chars, discarding HTML tags?
在此先感谢
推荐答案
我已经创建了一个解决方案,使用一个简单的过滤器和正则表达式的操作。
I've created a solution, using a simple filter and regex operations.
var appFilters = angular.module('myApp.filters', [])
.filter('limitHtml', function() {
return function(text, limit) {
var changedString = String(text).replace(/<[^>]+>/gm, '');
var length = changedString.length;
return changedString.length > limit ? changedString.substr(0, limit - 1) : changedString;
}
})
和记者使用,类似于 limitTo
过滤
and the correspondent usage, similar to limitTo
filter
<span ng-bind-html="text | limitHtml: maxNumberOfChar"></span>
请注意,在这种情况下,我也使用HTML结合,具体的我的解决方案。
Note that, in this case I am also using an html-binding, specific of my solution.
这篇关于使用HTML标签AngularJS limitTo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!