我有以下几点:

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

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

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


当前回答

<div>{{modal.title | slice: 0: 20}}</div>

其他回答

对我来说还行 'In span', ng-show = "MyCtrl.value.$viewValue. "长度> your_limit"…阅读更多。“结束时间”

如果你有两个绑定{{item.name}}和{{item.directory}}。

并且希望将数据显示为一个后跟名称的目录,假设目录为“/root”,名称为“Machine”(/root- Machine)。

{{[item.directory]+[isLast ? '': '/'] + [ item.name]  | limitTo:5}}

更优雅的解决方案:

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

我发现限制字符串长度的最简单的解决方案是{{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

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