我有以下几点:

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

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

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


当前回答

Use this in your html - {{value | limitTocustom:30 }}

and write this custom filter in your angular file,

app.filter('limitTocustom', function() {
    'use strict';
    return function(input, limit) {
        if (input) {
            if (limit > input.length) {
                return input.slice(0, limit);
            } else {
                return input.slice(0, limit) + '...';
            }
        }
    };
});

// if you initiate app name by variable app. eg: var app = angular.module('appname',[])

其他回答

在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;

        }


    }

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

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

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

我发现最简单的解决方案是让材料设计(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
}
Use this in your html - {{value | limitTocustom:30 }}

and write this custom filter in your angular file,

app.filter('limitTocustom', function() {
    'use strict';
    return function(input, limit) {
        if (input) {
            if (limit > input.length) {
                return input.slice(0, limit);
            } else {
                return input.slice(0, limit) + '...';
            }
        }
    };
});

// if you initiate app name by variable app. eg: var app = angular.module('appname',[])

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