我有以下几点:
<div>{{modal.title}}</div>
有没有一种方法可以限制字符串的长度,比如20个字符?
一个更好的问题是,有没有一种方法可以将字符串更改为截断并显示。如果超过20个字符?
我有以下几点:
<div>{{modal.title}}</div>
有没有一种方法可以限制字符串的长度,比如20个字符?
一个更好的问题是,有没有一种方法可以将字符串更改为截断并显示。如果超过20个字符?
当前回答
我发现最简单的解决方案是让材料设计(1.0.0-rc4)来做这项工作。md-input-container将为您完成这项工作。它连接了字符串,添加了省略,它还有一个额外的好处,允许你点击它来获得全文,所以它是整个玉米卷饼。您可能需要设置md-input-container的宽度。
HTML:
<md-input-container>
<md-select id="concat-title" placeholder="{{mytext}}" ng-model="mytext" aria-label="label">
<md-option ng-selected="mytext" >{{mytext}}
</md-option>
</md-select>
</md-input-container>
CS:
#concat-title .md-select-value .md-select-icon{
display: none; //if you want to show chevron remove this
}
#concat-title .md-select-value{
border-bottom: none; //if you want to show underline remove this
}
其他回答
编辑 AngularJSoffers的最新版本的limitTo过滤器。
你需要一个这样的自定义过滤器:
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 || ' …');
};
});
用法:
{{some_text | cut:true:100:' ...'}}
选项:
Wordwise (boolean) -如果为真,仅按单词边界切割, Max (integer) -文本的最大长度,切到这个字符数, Tail (string,默认值:'…')-将此字符串添加到输入 如果绳子被剪断,就用绳子。
另一个解决方案:http://ngmodules.org/modules/angularjs-truncate (by @Ehvince)
更优雅的解决方案:
HTML:
<html ng-app="phoneCat">
<body>
{{ "AngularJS string limit example" | strLimit: 20 }}
</body>
</html>
角代码:
var phoneCat = angular.module('phoneCat', []);
phoneCat.filter('strLimit', ['$filter', function($filter) {
return function(input, limit) {
if (! input) return;
if (input.length <= limit) {
return input;
}
return $filter('limitTo')(input, limit) + '...';
};
}]);
演示:
http://code-chunk.com/chunks/547bfb3f15aa1/str-limit-implementation-for-angularjs
你可以使用这个npm模块:https://github.com/sparkalow/angular-truncate
将截断过滤器注入到你的应用模块中,如下所示:
var myApp = angular.module('myApp', ['truncate']);
在你的应用程序中这样应用过滤器:
{{ text | characters:20 }}
你可以简单地在div中添加一个css类,并通过angularjs添加一个工具提示,这样鼠标移过去时就可以看到修剪后的文本。
< div class = " trim-info“工具提示= " {{modal.title}} > {{modal.title}} < / div > .trim-info { max-width: 50 px; 显示:inline-block; 溢出:隐藏; 文本溢出:省略; 空白:nowrap;} 行高:15 px; 位置:相对; }
可以使用筛选器限制字符串或数组的长度。看看AngularJS团队写的这个。