我有以下几点:

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

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

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


当前回答

<div>{{modal.title | slice: 0: 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>

更优雅的解决方案:

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

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

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

它将输出:

My String

如果你想要这样的东西: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…3720 df6680e17036.jar

这个解决方案纯粹是在HTML上使用ng标签。

解决方案是使用“show more…”限制显示的长文本。链接。如果用户点击“显示更多…”链接,它将显示其余的文本,并删除了“show more…”的链接。

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>