我有以下几点:

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

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

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


当前回答

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

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

它将输出:

My String

其他回答

ng-keypress = " filterValue(事件)”ng-model = "客户。CUSTOMER_PHONE”

美元的范围。filterValue = function($event){

        if(isNaN(String.fromCharCode($event.keyCode)) ){
            $event.preventDefault();
        }
        if($scope.customer.CUSTOMER_PHONE.length <= 11)
        {              
            $scope.customer.CUSTOMER_PHONE = $scope.customer.CUSTOMER_PHONE;
        }
        else
        {
            $event.preventDefault();
        }

    };

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

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

{{[item.directory]+[isLast ? '': '/'] + [ item.name]  | limitTo:5}}
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;

        }


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