使用 AngularJS 限制字符串的长度 [英] Limit the length of a string with AngularJS
本文介绍了使用 AngularJS 限制字符串的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下几点:
{{modal.title}}
有没有办法将字符串的长度限制为 20 个字符?
还有一个更好的问题是,如果字符串超过 20 个字符,我是否可以更改要截断的字符串并在末尾显示 ...
?
解决方案
编辑AngularJS
的最新版本提供了 limitTo
过滤器.
您需要一个自定义过滤器,如下所示:
angular.module('ng').filter('cut', function () {返回函数(值,逐字,最大值,尾){if (!value) 返回 '';max = parseInt(max, 10);if (!max) 返回值;if (value.length <= max) 返回值;value = value.substr(0, max);如果(逐字){var lastspace = value.lastIndexOf(' ');如果(最后一个空格!== -1){//也删除.和 ,所以它给出了一个更清晰的结果.if (value.charAt(lastspace-1) === '.' || value.charAt(lastspace-1) === ',') {lastspace = lastspace - 1;}value = value.substr(0, lastspace);}}返回值 + (tail || ' ...');};});
用法:
{{some_text |cut:true:100:' ...'}}
选项:
- wordwise (boolean) - 如果为 true,则仅按单词边界剪切,
- max (integer) - 文本的最大长度,剪切到这个字符数,
- tail (string, default: ' …') - 将此字符串添加到输入如果字符串被切断,则为字符串.
另一种解决方案:http://ngmodules.org/modules/angularjs-截断(@Ehvince)
I have the following:
<div>{{modal.title}}</div>
Is there a way that I could limit the length of the string to say 20 characters?
And an even better question would be is there a way that I could change the string to be truncated and show ...
at the end if it's more than 20 characters?
解决方案
Edit
The latest version of AngularJS
offers limitTo
filter.
You need a custom filter like this:
angular.module('ng').filter('cut', function () {
return function (value, wordwise, max, tail) {
if (!value) return '';
max = parseInt(max, 10);
if (!max) return value;
if (value.length <= max) return value;
value = value.substr(0, max);
if (wordwise) {
var lastspace = value.lastIndexOf(' ');
if (lastspace !== -1) {
//Also remove . and , so its gives a cleaner result.
if (value.charAt(lastspace-1) === '.' || value.charAt(lastspace-1) === ',') {
lastspace = lastspace - 1;
}
value = value.substr(0, lastspace);
}
}
return value + (tail || ' …');
};
});
Usage:
{{some_text | cut:true:100:' ...'}}
Options:
- wordwise (boolean) - if true, cut only by words bounds,
- max (integer) - max length of the text, cut to this number of chars,
- tail (string, default: ' …') - add this string to the input string if the string was cut.
Another solution: http://ngmodules.org/modules/angularjs-truncate (by @Ehvince)
这篇关于使用 AngularJS 限制字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文