限制与AngularJS一个字符串的长度 [英] Limit the length of a string with AngularJS

查看:1819
本文介绍了限制与AngularJS一个字符串的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

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

有没有办法,我可能会限制字符串的长度,说20个字符?

Is there a way that I could limit the length of the string to say 20 characters?

和一个更好的问题是有没有在年底被截断,我可以改变字符串的方式,并显示 ... 如果是超过20个字符?

And an even better question would be is there a way that I could change the string to be truncated and show ... at the end if it's more than 20 characters?

推荐答案

修改
AngularJS 最新版本提供 limitTo 过滤

Edit The latest version of AngularJSoffers limitTo filter.

您需要的自定义过滤器的是这样的:

angular.module('ng').filter('cut', function () {
        return function (value, wordwise, max, tail) {
            if (!value) return '';

            max = parseInt(max, 10);
            if (!max) return value;
            if (value.length <= max) return value;

            value = value.substr(0, max);
            if (wordwise) {
                var lastspace = value.lastIndexOf(' ');
                if (lastspace != -1) {
                    value = value.substr(0, lastspace);
                }
            }

            return value + (tail || ' …');
        };
    });

用法:

{{some_text | cut:true:100:' ...'}}

选项:


  • 字方式(布尔) - 如果为true,切只能通过文字范围,

  • MAX(整数) - 文字的最大长度,切到这个数字的字符,

  • 尾(字符串,默认:&NBSP;&hellip;) - 这个字符串添加到输入
          字符串如果字符串被切断。

  • 另一种解决方案:<一href=\"http://ngmodules.org/modules/angularjs-truncate\">http://ngmodules.org/modules/angularjs-truncate (由@Ehvince)

    Another solution: http://ngmodules.org/modules/angularjs-truncate (by @Ehvince)

    这篇关于限制与AngularJS一个字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆