使用AngularJS限制字符串的长度

234

我有以下内容:

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

有没有办法将字符串长度限制在20个字符以内?

更好的问题是,如果字符串超过20个字符,有没有办法将其截断并显示...?


3
http://jsfiddle.net/tUyyx/ - Ufuk Hacıoğulları
27个回答

510

这是一个简单的一行代码修复方案,不需要使用CSS。

{{ myString | limitTo: 20 }}{{myString.length > 20 ? '...' : ''}}

79
简洁优雅。您可以使用省略号的 HTML 实体'&hellip;'替代 '...' - Tom Harrison
可能是最无痛的解决方案。但仍需注意,过滤器相对较重,在大型ng-repeat列表上可能会有性能问题! :) - Cowwando
1
有没有一种方法可以在一定数量的行之后截断,而不是在一定数量的字符之后截断? - axd
@axd 你需要尝试在CSS中实现它,或编写一个指令来实现。 - Govan
1
这是最好的答案。如果使用合理数量的ng-repeat,性能影响应该可以忽略不计。如果您需要带回数百个需要被截断的ng-repeat内容,则可能需要重新考虑。很好的答案,@Govan。 - erier
显示剩余6条评论

349

编辑 最新版本的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:' ...'}}

选项:

  • wordwise(布尔值)- 如果为true,则仅按单词边界切割,
  • max(整数) - 文本的最大长度,将其裁剪为此字符数,
  • tail(字符串,默认值:' …') - 如果字符串被裁剪,则将此字符串添加到输入字符串中。

另一种解决方案http://ngmodules.org/modules/angularjs-truncate(作者:@Ehvince)


2
在Angular模块中有一个等价物:http://ngmodules.org/modules/angularjs-truncate - Ehvince
当我们像这样使用时,它可以正常工作: {{post.post_content | cut:true:100:' ...'}} 但是,当我像这样使用时会失败: <span ng-bind-html="trustedHtml(post.post_content| cut:true:100:' ...')"></span> 因为在我的情况下,我被迫使用受信任的HTML。 - S Vinesh
逐字限制是一个很好的功能,似乎在默认的“limitTo”中不存在。 - pdizz
有没有一种简单的方法filterTo,使字符串在位置限制后第一个空格处截断?这样它就不会在单词中间分割。 - Ellone
我只是想稍微改进一下这个答案,如果换行的最后一个单词以逗号或句号结尾,它会以....或,...结束,这让我很不爽,所以可以在最后一个lastspace != -1 if语句之后添加以下内容来改进: if (value.charAt(lastspace-1) == '.' || value.charAt(lastspace-1) == ',') { lastspace = lastspace - 1; } - JDDelgado
显示剩余5条评论

61

我知道现在有些晚了,但在最新版本的angularjs中(我使用的是1.2.16),limitTo过滤器支持字符串和数组,所以你可以像这样限制字符串长度:

{{ "My String Is Too Long" | limitTo: 9 }}

这将输出:

My String

9
这个解决方案缺少了“...”。结果应该是:“我的字符串……” - Snæbjørn
我在这里看不到省略号:http://plnkr.co/edit/HyAejS2DY781bqcT0RgV?p=preview。你能详细说明一下吗? - slim
2
@Snæbjørn 的意思是,提问者更喜欢在截断的字符串末尾插入“...”的解决方案。Govan的答案做到了这一点。 - Nahn
@Nahn 感谢您指出这一点。我可能应该在 EpokK 的答案下发表评论,而不是另一个答案。 - slim

52

您只需将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;
   }

4
文本溢出:省略号,不错的选择。 - Chris Russo
4
这种技术很棒,但会防止文字自动换行。 - Larry
这是正确的答案。我的一般准则是:“不要在 JavaScript 中做可以在 CSS 中完成的事情”。 - aidan
4
这仅适用于每段只有一行文本的情况。如需多行文本,请参见 https://css-tricks.com/line-clampin/(并非所有浏览器都支持此功能)。 - Robert
这是一个完美的纯CSS解决方案,适用于单行 - 如果需要多行,则由于“white-space:nowrap;”而无法工作。 - Ignacio Vazquez
显示剩余2条评论

27

我曾经遇到过类似的问题,这是我所做的:

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

我会删除两个输出之间的空格,以避免换行。 - Ignacio Vazquez

22
< div >{{modal.title | limitTo:20}}...< / div>

最简单的方法,但是它假设每个标题都有超过20个字符,这在某些情况下可能是意外的。 - Henrique M.

18

更优雅的解决方案:

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值是动态的情况下添加一个return吗?即,if(!input){return;} 否则会出现JS控制台错误。 - mcranston18
1
@mcranston18已添加。谢谢。 - Anam

15

由于我们只需要在字符串长度超过限制时才使用省略号,因此使用ng-if添加省略号似乎比绑定更为合适。

{{ longString | limitTo: 20 }}<span ng-if="longString.length > 20">&hellip;</span>

11

7

这里有一个选项。

.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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接