我有以下几点:

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

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

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


当前回答

我发现最简单的解决方案是让材料设计(1.0.0-rc4)来做这项工作。md-input-container将为您完成这项工作。它连接了字符串,添加了省略,它还有一个额外的好处,允许你点击它来获得全文,所以它是整个玉米卷饼。您可能需要设置md-input-container的宽度。

HTML:

<md-input-container>
   <md-select id="concat-title" placeholder="{{mytext}}" ng-model="mytext" aria-label="label">
      <md-option ng-selected="mytext" >{{mytext}}
      </md-option>
   </md-select>
</md-input-container>

CS:

#concat-title .md-select-value .md-select-icon{
   display: none; //if you want to show chevron remove this
}
#concat-title .md-select-value{
   border-bottom: none; //if you want to show underline remove this
}

其他回答

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

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

在html中,它与angular自身提供的limitTo过滤器一起使用,如下所示:

    <p> {{limitTo:30 | keepDots }} </p>

filter keepDots:

     App.filter('keepDots' , keepDots)

       function keepDots() {

        return function(input,scope) {
            if(!input) return;

             if(input.length > 20)
                return input+'...';
            else
                return input;

        }


    }

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

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

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

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

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

你可以使用这个npm模块:https://github.com/sparkalow/angular-truncate

将截断过滤器注入到你的应用模块中,如下所示:

var myApp = angular.module('myApp', ['truncate']); 

在你的应用程序中这样应用过滤器:

{{ text | characters:20 }}