У меня есть следующее:
<div>{{modal.title}}</div>
Есть ли способ, которым я мог бы ограничить длину строки, чтобы сказать 20 символов?
И еще лучший вопрос заключается в том, что я могу изменить строку, которая будет усечена, и показать ...
в конце, если она содержит более 20 символов?
Edit
Последняя версия AngularJS
предлагает limitTo
filter.
Вам нужен специальный фильтр:
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 (by @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; }
У меня была аналогичная проблема, вот что я сделал:
{{ longString | limitTo: 20 }} {{longString.length < 20 ? '' : '...'}}
Более элегантное решение:
HTML:
<html ng-app="phoneCat">
<body>
{{ "AngularJS string limit example" | strLimit: 20 }}
</body>
</html>
Angular Код:
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
Так как нам нужен эллипс только тогда, когда длина строки превышает лимит, представляется более целесообразным добавить многоточие, используя ng-if
, чем привязку.
{{ longString | limitTo: 20 }}<span ng-if="longString.length > 20">…</span>
< div >{{modal.title | limitTo:20}}...< / div>
Существует опция
.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>
Здесь пользовательский фильтр для усечения текста. Это вдохновило решение 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...");
});
});
В html он используется вместе с limitTo фильтром, предоставленным самим angular, как показано ниже,
<p> {{limitTo:30 | keepDots }} </p>
фильтр keepDots:
App.filter('keepDots' , keepDots)
function keepDots() {
return function(input,scope) {
if(!input) return;
if(input.length > 20)
return input+'...';
else
return input;
}
}
Вы можете ограничить длину строки или массива с помощью фильтра. Проверьте этот, написанный командой AngularJS.
Самое простое решение, которое я нашел для простого ограничения длины строки, было {{ 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
Если вам нужно что-то вроде: InputString = > StringPart1... StringPart2
HTML:
<html ng-app="myApp">
<body>
{{ "AngularJS string limit example" | strLimit: 10 : 20 }}
</body>
</html>
Angular Код:
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
Это может быть не от конца script, но вы можете использовать приведенный ниже css и добавить этот класс в div. Это усекает текст, а также покажет полный текст при наведении курсора мыши. Вы можете добавить больше текста и добавить angular click hadler, чтобы изменить класс div на cli
.ellipseContent {
overflow: hidden;
white-space: nowrap;
-ms-text-overflow: ellipsis;
text-overflow: ellipsis;
}
.ellipseContent:hover {
overflow: visible;
white-space: normal;
}
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',[])
САМОЕ ЛУЧШЕЕ РЕШЕНИЕ → я нашел, чтобы позволить Material Design (1.0.0-rc4) выполнять эту работу. md-input-container
будет работать для вас. Он объединяет строку и добавляет elipses, плюс у нее есть дополнительное преимущество, позволяющее вам щелкнуть по ней, чтобы получить полный текст, чтобы он был полностью enchilada. Вам может потребоваться установить ширину 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
}
Вы можете использовать этот модуль npm: https://github.com/sparkalow/angular-truncate
Внесите фильтр усечения в свой модуль приложения следующим образом:
var myApp = angular.module('myApp', ['truncate']);
и примените фильтр в своем приложении следующим образом:
{{ text | characters:20 }}
Я использую хороший набор полезной библиотеки фильтров "Angular -filter", и один из них называется "truncate" тоже полезен.
https://github.com/a8m/angular-filter#truncate
используется:
text | truncate: [length]: [suffix]: [preserve-boolean]
Если у вас есть две привязки {{item.name}}
и {{item.directory}}
.
И хотите показать данные как каталог, за которым следует имя, при условии, что "/root" - это каталог и "машина" в качестве имени (/root-machine).
{{[item.directory]+[isLast ? '': '/'] + [ item.name] | limitTo:5}}
Это нормально для меня 'In span', ng-show = "MyCtrl.value. $ViewValue.length > your_limit"... далее. 'end span'
Ограничить количество слов с помощью настраиваемого фильтра Angular: Вот как я использовал фильтр Angular, чтобы ограничить количество отображаемых слов с помощью настраиваемого фильтра.
HTML:
<span>{{dataModelObject.TextValue | limitWordsTo: 38}} ......</span>
Angular/Javascript Code
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
Это решение чисто использует тег ng в HTML.
Решение состоит в том, чтобы ограничить длинный текст, отображаемый ссылкой "показать больше..." в конце его. Если пользователь нажмет ссылку "показать больше..." , он покажет остальную часть текста и удалит ссылку "показать больше..." .
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: ')';
}