我有以下几点:
<div>{{modal.title}}</div>
有没有一种方法可以限制字符串的长度,比如20个字符?
一个更好的问题是,有没有一种方法可以将字符串更改为截断并显示。如果超过20个字符?
我有以下几点:
<div>{{modal.title}}</div>
有没有一种方法可以限制字符串的长度,比如20个字符?
一个更好的问题是,有没有一种方法可以将字符串更改为截断并显示。如果超过20个字符?
当前回答
我将使用以下三元操作符替代来完成截断…遵循:
<div>{{ modal.title.length > 20 ? (modal.title | limitTo : 20) + '...' : modal.title }}</div>
其他回答
这可能不是来自脚本末尾,但你可以使用下面的css并将这个类添加到div中。这将截断文本,并在鼠标悬停时显示全文。你可以添加更多的文本,并添加一个角点击手柄来改变cli上的div类
.ellipseContent {
overflow: hidden;
white-space: nowrap;
-ms-text-overflow: ellipsis;
text-overflow: ellipsis;
}
.ellipseContent:hover {
overflow: visible;
white-space: normal;
}
这个解决方案纯粹是在HTML上使用ng标签。
解决方案是使用“show more…”限制显示的长文本。链接。如果用户点击“显示更多…”链接,它将显示其余的文本,并删除了“show more…”的链接。
HTML:
<div ng-init="limitText=160">
<p>{{ veryLongText | limitTo: limitText }}
<a href="javascript:void(0)"
ng-hide="veryLongText.length < limitText"
ng-click="limitText = veryLongText.length + 1" > show more..
</a>
</p>
</div>
我创建了这个指令,很容易做到这一点,截断字符串到指定的限制,并添加了一个“显示更多/更少”切换。你可以在GitHub上找到它:https://github.com/doukasd/AngularJS-Components
它可以这样使用:
<p data-dd-collapse-text="100">{{veryLongText}}</p>
下面是指令:
// a directive to auto-collapse long text
app.directive('ddCollapseText', ['$compile', function($compile) {
return {
restrict: 'A',
replace: true,
link: function(scope, element, attrs) {
// start collapsed
scope.collapsed = false;
// create the function to toggle the collapse
scope.toggle = function() {
scope.collapsed = !scope.collapsed;
};
// get the value of the dd-collapse-text attribute
attrs.$observe('ddCollapseText', function(maxLength) {
// get the contents of the element
var text = element.text();
if (text.length > maxLength) {
// split the text in two parts, the first always showing
var firstPart = String(text).substring(0, maxLength);
var secondPart = String(text).substring(maxLength, text.length);
// create some new html elements to hold the separate info
var firstSpan = $compile('<span>' + firstPart + '</span>')(scope);
var secondSpan = $compile('<span ng-if="collapsed">' + secondPart + '</span>')(scope);
var moreIndicatorSpan = $compile('<span ng-if="!collapsed">...</span>')(scope);
var toggleButton = $compile('<span class="collapse-text-toggle" ng-click="toggle()">{{collapsed ? "less" : "more"}}</span>')(scope);
// remove the current contents of the element
// and add the new ones we created
element.empty();
element.append(firstSpan);
element.append(secondSpan);
element.append(moreIndicatorSpan);
element.append(toggleButton);
}
});
}
};
}]);
和一些CSS去它:
.collapse-text-toggle {
font-size: 0.9em;
color: #666666;
cursor: pointer;
}
.collapse-text-toggle:hover {
color: #222222;
}
.collapse-text-toggle:before {
content: '\00a0(';
}
.collapse-text-toggle:after {
content: ')';
}
< div >{{modal.title | limitTo:20}}...< / div>
<div>{{modal.title | slice: 0: 20}}</div>