Answers:
编辑
最新版本的AngularJS
报价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:' ...'}}
另一个解决方案:http ://ngmodules.org/modules/angularjs-truncate(@Ehvince提供)
这是没有css的简单的单行修复。
{{ myString | limitTo: 20 }}{{myString.length > 20 ? '...' : ''}}
'...'
您也可以将HTML实体用于省略号:'…'
我知道这很晚,但是在最新版本的angularjs(我使用的是1.2.16)中,limitTo过滤器支持字符串以及数组,因此您可以像这样限制字符串的长度:
{{ "My String Is Too Long" | limitTo: 9 }}
将输出:
My String
您可以简单地将css类添加到div,并通过angularjs添加工具提示,以便在鼠标悬停时可以看到修剪的文本。
<div class="trim-info" tooltip="{{modal.title}}">{{modal.title}}</div> .trim-info { max-width: 50px; display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 15px; position: relative; }
ng-repeat
。
我有一个类似的问题,这是我所做的:
{{ longString | limitTo: 20 }} {{longString.length < 20 ? '' : '...'}}
< div >{{modal.title | limitTo:20}}...< / div>
更优雅的解决方案:
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
input
值是动态的,我可以建议添加收益吗?即if (!input) {return;}
否则将出现JS控制台错误
有一个选择
.text {
max-width: 140px;
white-space: nowrap;
overflow: hidden;
padding: 5px;
text-overflow: ellipsis;(...)
}
<div class="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi qui soluta labore! Facere nisi aperiam sequi dolores voluptatum delectus vel vero animi, commodi harum molestias deleniti, quasi nesciunt. Distinctio veniam minus ut vero rerum debitis placeat veritatis doloremque laborum optio, nemo quibusdam ad, sed cum quas maxime hic enim sint at quos cupiditate qui eius quam tempora. Ab sint in sunt consequuntur assumenda ratione voluptates dicta dolor aliquid at esse quaerat ea, veritatis reiciendis, labore repellendus rem optio debitis illum! Eos dignissimos, atque possimus, voluptatibus similique error. Perferendis error doloribus harum enim dolorem, suscipit unde vel, totam in quia mollitia.</div>
我发现的用于简单限制字符串长度的最简单解决方案是{{ modal.title | slice:0:20 }}
,然后从上述@Govan借用,{{ modal.title.length > 20 ? '...' : ''}}
如果字符串长于20,则可以用来添加悬浮点,因此最终结果很简单:
{{ modal.title | slice:0:20 }}{{ modal.title.length > 20 ? '...' : ''}}
https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html
这是一个用于截断文本的自定义过滤器。它受到EpokK解决方案的启发,但根据我的需要和口味进行了修改。
angular.module('app').filter('truncate', function () {
return function (content, maxCharacters) {
if (content == null) return "";
content = "" + content;
content = content.trim();
if (content.length <= maxCharacters) return content;
content = content.substring(0, maxCharacters);
var lastSpace = content.lastIndexOf(" ");
if (lastSpace > -1) content = content.substr(0, lastSpace);
return content + '...';
};
});
这是单元测试,因此您可以看到它的行为方式:
describe('truncate filter', function () {
var truncate,
unfiltered = " one two three four ";
beforeEach(function () {
module('app');
inject(function ($filter) {
truncate = $filter('truncate');
});
});
it('should be defined', function () {
expect(truncate).to.be.ok;
});
it('should return an object', function () {
expect(truncate(unfiltered, 0)).to.be.ok;
});
it('should remove leading and trailing whitespace', function () {
expect(truncate(unfiltered, 100)).to.equal("one two three four");
});
it('should truncate to length and add an ellipsis', function () {
expect(truncate(unfiltered, 3)).to.equal("one...");
});
it('should round to word boundaries', function () {
expect(truncate(unfiltered, 10)).to.equal("one two...");
});
it('should split a word to avoid returning an empty string', function () {
expect(truncate(unfiltered, 2)).to.equal("on...");
});
it('should tolerate non string inputs', function () {
expect(truncate(434578932, 4)).to.equal("4345...");
});
it('should tolerate falsey inputs', function () {
expect(truncate(0, 4)).to.equal("0");
expect(truncate(false, 4)).to.equal("fals...");
});
});
如果您想要这样的东西: InputString => StringPart1 ... StringPart2
HTML:
<html ng-app="myApp">
<body>
{{ "AngularJS string limit example" | strLimit: 10 : 20 }}
</body>
</html>
角度代码:
var myApp = angular.module('myApp', []);
myApp.filter('strLimit', ['$filter', function($filter) {
return function(input, beginlimit, endlimit) {
if (! input) return;
if (input.length <= beginlimit + endlimit) {
return input;
}
return $filter('limitTo')(input, beginlimit) + '...' + $filter('limitTo')(input, -endlimit) ;
};
}]);
具有以下参数的示例:
beginLimit = 10
endLimit = 20
之前:-/ home / house/room/etc / ava_B0363852D549079E3720DF6680E17036.jar
之后:--/ home/hous...3720DF6680E17036.jar
Use this in your html - {{value | limitTocustom:30 }}
and write this custom filter in your angular file,
app.filter('limitTocustom', function() {
'use strict';
return function(input, limit) {
if (input) {
if (limit > input.length) {
return input.slice(0, limit);
} else {
return input.slice(0, limit) + '...';
}
}
};
});
// if you initiate app name by variable app. eg: var app = angular.module('appname',[])
如果您有两个绑定{{item.name}}
和{{item.directory}}
。
并希望将数据显示为目录,然后显示名称,并假设目录以“ / root”,名称为“ / Machine”(/ root-machine)。
{{[item.directory]+[isLast ? '': '/'] + [ item.name] | limitTo:5}}
您可以使用以下npm模块:https : //github.com/sparkalow/angular-truncate
将截断过滤器注入到您的应用程序模块中,如下所示:
var myApp = angular.module('myApp', ['truncate']);
并通过以下方式在您的应用中应用过滤器:
{{ text | characters:20 }}
我创建了此指令,该指令很容易做到,将字符串截断到指定的限制并添加“显示更多/更少”切换。您可以在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: ')';
}
此解决方案仅在HTML上使用ng标签。
解决方案是限制显示在其末尾带有“显示更多...”链接的长文本。如果用户单击“显示更多...”链接,它将显示其余文本,并删除了“显示更多...”链接。
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>
最简单的解决方案->我发现是让Material Design(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
}
使用自定义Angular过滤器限制单词数: 这是我使用Angular过滤器来限制使用自定义过滤器显示的单词数的方法。
HTML:
<span>{{dataModelObject.TextValue | limitWordsTo: 38}} ......</span>
Angular / Javascript代码
angular.module('app')
.filter('limitWordsTo', function () {
return function (stringData, numberOfWords) {
//Get array of words (determined by spaces between words)
var arrayOfWords = stringData.split(" ");
//Get loop limit
var loopLimit = numberOfWords > arrayOfWords.length ? arrayOfWords.length : numberOfWords;
//Create variables to hold limited word string and array iterator
var limitedString = '', i;
//Create limited string bounded by limit passed in
for (i = 0; i < loopLimit; i++) {
if (i === 0) {
limitedString = arrayOfWords[i];
} else {
limitedString = limitedString + ' ' + arrayOfWords[i];
}
}
return limitedString;
};
}); //End filter
我使用了一组有用的过滤器库“ Angular-filter”,其中一个名为“ truncate”也是有用的。
https://github.com/a8m/angular-filter#truncate
用法是:
text | truncate: [length]: [suffix]: [preserve-boolean]