我有以下几点:

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

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

一个更好的问题是,有没有一种方法可以将字符串更改为截断并显示。如果超过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:

<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

我使用了一套非常有用的滤镜库“Angular-filter”,其中一个叫做“truncate”的也很有用。

https://github.com/a8m/angular-filter#truncate

用法是:

text | truncate: [length]: [suffix]: [preserve-boolean]

可以使用筛选器限制字符串或数组的长度。看看AngularJS团队写的这个。

我发现限制字符串长度的最简单的解决方案是{{modal。title | slice:0:20}},然后借用上面的@Govan,你可以使用{{modal.title.length > 20 ?“…': "}}如果字符串长于20,则添加挂起点,因此最终结果很简单:

{{模态。Title | slice:0:20}}{{modal.title.length > 20 ?“…': "}}

https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html

使用自定义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