232

我有以下内容:

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

有没有办法可以将字符串的长度限制为 20 个字符?

一个更好的问题是,如果字符串...超过 20 个字符,我是否可以更改要截断的字符串并在末尾显示?

4

26 回答 26

504

这是没有 css 的简单的一行修复。

{{ myString | limitTo: 20 }}{{myString.length > 20 ? '...' : ''}}
于 2014-09-17T13:49:26.747 回答
349

编辑 最新版本的AngularJS优惠limitTo过滤器

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

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) {
                  //Also remove . and , so its gives a cleaner result.
                  if (value.charAt(lastspace-1) === '.' || value.charAt(lastspace-1) === ',') {
                    lastspace = lastspace - 1;
                  }
                  value = value.substr(0, lastspace);
                }
            }

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

用法:

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

选项:

  • wordwise (boolean) - 如果为真,则仅按单词边界切割,
  • max (integer) - 文本的最大长度,剪切到这个字符数,
  • tail (string, default: ' ...') - 如果字符串被剪切,则将此字符串添加到输入字符串中。

另一个解决方案http ://ngmodules.org/modules/angularjs-truncate(@Ehvince)

于 2013-08-07T06:24:54.330 回答
61

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

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

这将输出:

My String
于 2014-05-09T14:42:17.643 回答
52

您可以简单地向 div 添加一个 css 类,并通过 angularjs 添加一个工具提示,以便在鼠标悬停时可以看到修剪后的文本。

<div class="trim-info" tooltip="{{modal.title}}">{{modal.title}}</div>

   .trim-info {
      max-width: 50px;
      display: inline-block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;  
      line-height: 15px;
      position: relative;
   }
于 2013-08-07T06:42:51.657 回答
27

我有一个类似的问题,这就是我所做的:

{{ longString | limitTo: 20 }} {{longString.length < 20 ? '' : '...'}}
于 2014-12-19T20:51:12.150 回答
22
< div >{{modal.title | limitTo:20}}...< / div>
于 2016-07-15T18:51:07.663 回答
18

更优雅的解决方案:

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

于 2014-12-01T05:28:08.730 回答
15

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

{{ longString | limitTo: 20 }}<span ng-if="longString.length > 20">&hellip;</span>
于 2016-02-12T20:49:22.113 回答
9

我找到的简单限制字符串长度的最简单解决方案是{{ modal.title | slice:0:20 }},然后从上面的@Govan 借用,{{ modal.title.length > 20 ? '...' : ''}}如果字符串长度超过 20,您可以使用它来添加暂停点,所以最终结果很简单:

{{ modal.title | slice:0:20 }}{{ modal.title.length > 20 ? '...' : ''}}

https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html

于 2017-06-05T21:25:42.607 回答
7

有一个选项

.text {
            max-width: 140px;
            white-space: nowrap;
            overflow: hidden;
            padding: 5px;
            text-overflow: ellipsis;(...)
        }
<div class="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi qui soluta labore! Facere nisi aperiam sequi dolores voluptatum delectus vel vero animi, commodi harum molestias deleniti, quasi nesciunt. Distinctio veniam minus ut vero rerum debitis placeat veritatis doloremque laborum optio, nemo quibusdam ad, sed cum quas maxime hic enim sint at quos cupiditate qui eius quam tempora. Ab sint in sunt consequuntur assumenda ratione voluptates dicta dolor aliquid at esse quaerat ea, veritatis reiciendis, labore repellendus rem optio debitis illum! Eos dignissimos, atque possimus, voluptatibus similique error. Perferendis error doloribus harum enim dolorem, suscipit unde vel, totam in quia mollitia.</div>

于 2016-08-29T09:49:37.110 回答
4

这是用于截断文本的自定义过滤器。它的灵感来自 EpokK 的解决方案,但根据我的需要和口味进行了修改。

angular.module('app').filter('truncate', function () {

    return function (content, maxCharacters) {

        if (content == null) return "";

        content = "" + content;

        content = content.trim();

        if (content.length <= maxCharacters) return content;

        content = content.substring(0, maxCharacters);

        var lastSpace = content.lastIndexOf(" ");

        if (lastSpace > -1) content = content.substr(0, lastSpace);

        return content + '...';
    };
});

这里是单元测试,所以你可以看到它应该如何表现:

describe('truncate filter', function () {

    var truncate,
        unfiltered = " one two three four ";

    beforeEach(function () {

        module('app');

        inject(function ($filter) {

            truncate = $filter('truncate');
        });
    });

    it('should be defined', function () {

        expect(truncate).to.be.ok;
    });

    it('should return an object', function () {

        expect(truncate(unfiltered, 0)).to.be.ok;
    });

    it('should remove leading and trailing whitespace', function () {

        expect(truncate(unfiltered, 100)).to.equal("one two three four");
    });

    it('should truncate to length and add an ellipsis', function () {

        expect(truncate(unfiltered, 3)).to.equal("one...");
    });

    it('should round to word boundaries', function () {

        expect(truncate(unfiltered, 10)).to.equal("one two...");
    });

    it('should split a word to avoid returning an empty string', function () {

        expect(truncate(unfiltered, 2)).to.equal("on...");
    });

    it('should tolerate non string inputs', function () {

        expect(truncate(434578932, 4)).to.equal("4345...");
    });

    it('should tolerate falsey inputs', function () {

        expect(truncate(0, 4)).to.equal("0");

        expect(truncate(false, 4)).to.equal("fals...");
    });
});
于 2014-11-01T08:59:02.440 回答
3

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

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

过滤保持点:

     App.filter('keepDots' , keepDots)

       function keepDots() {

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

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

        }


    }
于 2015-02-01T11:53:35.447 回答
3

您可以使用过滤器来限制字符串或数组的长度。检查这个由 AngularJS 团队编写的。

于 2014-02-12T06:04:37.120 回答
3

如果你想要类似的东西: InputString => StringPart1 ... StringPart2

HTML:

<html ng-app="myApp">
  <body>
    {{ "AngularJS string limit example" | strLimit: 10 : 20 }}
  </body>
</html>

角代码:

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

 myApp.filter('strLimit', ['$filter', function($filter) {
   return function(input, beginlimit, endlimit) {
      if (! input) return;
      if (input.length <= beginlimit + endlimit) {
          return input;
      }

      return $filter('limitTo')(input, beginlimit) + '...' + $filter('limitTo')(input, -endlimit) ;
   };
}]);

具有以下参数的示例:
beginLimit = 10
endLimit = 20

之前: - /home/house/room/etc/ava_B0363852D549079E3720DF6680E17036.jar
之后: - /home/house...3720DF6680E17036.jar

于 2016-10-05T13:06:46.703 回答
2
<div>{{modal.title | slice: 0: 20}}</div>
于 2019-08-20T08:01:35.467 回答
2
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',[])
于 2015-12-08T12:55:38.010 回答
2

这可能不是来自脚本端,但您可以使用下面的 css 并将此类添加到 div。这将截断文本并在鼠标悬停时显示全文。您可以添加更多文本并添加角度单击 hadler 以更改 cli 上的 div 类

.ellipseContent {
    overflow: hidden;
    white-space: nowrap;
    -ms-text-overflow: ellipsis;
    text-overflow: ellipsis;
}

    .ellipseContent:hover {
        overflow: visible;
        white-space: normal;
    }
于 2016-02-11T19:23:11.403 回答
2

如果您有两个绑定{{item.name}}{{item.directory}}.

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

{{[item.directory]+[isLast ? '': '/'] + [ item.name]  | limitTo:5}}
于 2017-08-16T22:32:03.267 回答
1

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

像这样将截断过滤器注入您的应用程序模块:

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

并以这种方式在您的应用中应用过滤器:

{{ text | characters:20 }} 
于 2015-10-29T10:22:20.407 回答
1

我将使用以下三元运算符替代方法来完成截断,...如下所示:

<div>{{ modal.title.length > 20 ? (modal.title | limitTo : 20) + '...' : modal.title }}</div>
于 2020-11-16T13:56:02.960 回答
0

我创建了这个指令,它很容易做到这一点,将字符串截断到指定的限制,并添加一个“显示更多/更少”切换。你可以在 GitHub 上找到它:https ://github.com/doukasd/AngularJS-Components

它可以这样使用:

<p data-dd-collapse-text="100">{{veryLongText}}</p>

这是指令:

// a directive to auto-collapse long text
app.directive('ddCollapseText', ['$compile', function($compile) {
return {
    restrict: 'A',
    replace: true,
    link: function(scope, element, attrs) {

        // start collapsed
        scope.collapsed = false;

        // create the function to toggle the collapse
        scope.toggle = function() {
            scope.collapsed = !scope.collapsed;
        };

        // get the value of the dd-collapse-text attribute
        attrs.$observe('ddCollapseText', function(maxLength) {
            // get the contents of the element
            var text = element.text();

            if (text.length > maxLength) {
                // split the text in two parts, the first always showing
                var firstPart = String(text).substring(0, maxLength);
                var secondPart = String(text).substring(maxLength, text.length);

                // create some new html elements to hold the separate info
                var firstSpan = $compile('<span>' + firstPart + '</span>')(scope);
                var secondSpan = $compile('<span ng-if="collapsed">' + secondPart + '</span>')(scope);
                var moreIndicatorSpan = $compile('<span ng-if="!collapsed">...</span>')(scope);
                var toggleButton = $compile('<span class="collapse-text-toggle" ng-click="toggle()">{{collapsed ? "less" : "more"}}</span>')(scope);

                // remove the current contents of the element
                // and add the new ones we created
                element.empty();
                element.append(firstSpan);
                element.append(secondSpan);
                element.append(moreIndicatorSpan);
                element.append(toggleButton);
            }
        });
    }
};
}]);

还有一些与之配套的 CSS:

.collapse-text-toggle {
font-size: 0.9em;
color: #666666;
cursor: pointer;
}
.collapse-text-toggle:hover {
color: #222222;
}
.collapse-text-toggle:before {
content: '\00a0(';
}
.collapse-text-toggle:after {
content: ')';
}
于 2014-08-07T14:52:55.340 回答
0

This solution is purely using ng tag on HTML.

The solution is to limit the long text displayed with 'show more...' link at the end of it. If user click 'show more...' link, it will show the rest of the text and removed the 'show more...' link.

HTML:

<div ng-init="limitText=160">
   <p>{{ veryLongText | limitTo: limitText }} 
       <a href="javascript:void(0)" 
           ng-hide="veryLongText.length < limitText" 
           ng-click="limitText = veryLongText.length + 1" > show more..
       </a>
   </p>
</div>
于 2015-12-17T10:59:55.100 回答
0

'In span' 对我来说没问题,ng-show = "MyCtrl.value.$viewValue.length > your_limit" ...阅读更多。'结束跨度'

于 2016-08-12T05:22:22.020 回答
0

使用自定义 Angular 过滤器限制字数: 这是我如何使用 Angular 过滤器来限制使用自定义过滤器显示的字数。

HTML:

<span>{{dataModelObject.TextValue | limitWordsTo: 38}} ......</span>

Angular/Javascript 代码

angular.module('app')
.filter('limitWordsTo', function () {
    return function (stringData, numberOfWords) {
        //Get array of words (determined by spaces between words)
        var arrayOfWords = stringData.split(" ");

        //Get loop limit
        var loopLimit = numberOfWords > arrayOfWords.length ? arrayOfWords.length : numberOfWords;

        //Create variables to hold limited word string and array iterator
        var limitedString = '', i;
        //Create limited string bounded by limit passed in
        for (i = 0; i < loopLimit; i++) {
            if (i === 0) {
                limitedString = arrayOfWords[i];
            } else {
                limitedString = limitedString + ' ' + arrayOfWords[i];
            }
        }
        return limitedString;
    }; 
}); //End filter
于 2016-06-01T18:52:26.173 回答
0

我使用了一组很好的有用的过滤器库“Angular-filter”,其中一个叫做“truncate”也很有用。

https://github.com/a8m/angular-filter#truncate

用法是:

text | truncate: [length]: [suffix]: [preserve-boolean]
于 2017-09-29T09:28:00.480 回答
0

最简单的解决方案 --> 我发现让 Material Design (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
}
于 2016-02-16T16:30:30.733 回答