我有以下几点:

<div>{{modal.title}}</div>

有没有一种方法可以限制字符串的长度,比如20个字符?

一个更好的问题是,有没有一种方法可以将字符串更改为截断并显示。如果超过20个字符?


当前回答

使用自定义Angular过滤器限制字数: 下面是我如何使用Angular过滤器来限制使用自定义过滤器显示的字数。

HTML:

<span>{{dataModelObject.TextValue | limitWordsTo: 38}} ......</span>

角/ 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

其他回答

我也遇到过类似的问题,我是这样做的:

{{ longString | limitTo: 20 }} {{longString.length < 20 ? '' : '...'}}

编辑 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)

这可能不是来自脚本末尾,但你可以使用下面的css并将这个类添加到div中。这将截断文本,并在鼠标悬停时显示全文。你可以添加更多的文本,并添加一个角点击手柄来改变cli上的div类

.ellipseContent {
    overflow: hidden;
    white-space: nowrap;
    -ms-text-overflow: ellipsis;
    text-overflow: ellipsis;
}

    .ellipseContent:hover {
        overflow: visible;
        white-space: normal;
    }

使用自定义Angular过滤器限制字数: 下面是我如何使用Angular过滤器来限制使用自定义过滤器显示的字数。

HTML:

<span>{{dataModelObject.TextValue | limitWordsTo: 38}} ......</span>

角/ 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

我创建了这个指令,很容易做到这一点,截断字符串到指定的限制,并添加了一个“显示更多/更少”切换。你可以在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: ')';
}