使用AngularJS限制字符串的长度

时间:2013-08-07 06:00:45

标签: angularjs filter angularjs-filter

我有以下内容:

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

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

还有一个更好的问题是,如果字符串超过20个字符,我可以将字符串更改为截断字符串并在结尾显示...吗?

26 个答案:

答案 0 :(得分:487)

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

{{ myString | limitTo: 20 }}{{myString.length > 20 ? '...' : ''}}

答案 1 :(得分:340)

修改 最新版本的AngularJS提供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) {
                  //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) - 如果为true,则仅按字边界切割,
  • max(整数) - 文本的最大长度,减少到此字符数,
  • tail(string,default:'...') - 将此字符串添加到输入中       如果字符串被剪切,则为字符串。

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

答案 2 :(得分:57)

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

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

将输出:

My String

答案 3 :(得分:50)

你可以简单地将一个css类添加到div中,并通过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;
   }

答案 4 :(得分:27)

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

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

答案 5 :(得分:17)

更优雅的解决方案:

HTML:

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

Angular Code:

 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

答案 6 :(得分:17)

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

答案 7 :(得分:15)

Since we need ellipsis only when the string length is over the limit, it seems more appropriate to add ellipsis by using #include "SomeHeader.h" int main() { Nodes<int> someNodes(); return 0; } than binding.

ng-if

答案 8 :(得分:7)

有一个选项

&#13;
&#13;
.text {
            max-width: 140px;
            white-space: nowrap;
            overflow: hidden;
            padding: 5px;
            text-overflow: ellipsis;(...)
        }
&#13;
<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>
&#13;
&#13;
&#13;

答案 9 :(得分:4)

The simplest solution I found简单地限制字符串长度为{{ modal.title | slice:0:20 }},然后从上面的@Govan借用,如果字符串长于20,则可以使用{{ modal.title.length > 20 ? '...' : ''}}添加暂停点,所以最终结果很简单:

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

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

答案 10 :(得分: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...");
    });
});

答案 11 :(得分:3)

您可以使用过滤器限制字符串或数组的长度。检查AngularJS团队撰写的this one

答案 12 :(得分:3)

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

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

过滤器keepDots:

     App.filter('keepDots' , keepDots)

       function keepDots() {

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

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

        }


    }

答案 13 :(得分:3)

如果您需要以下内容: InputString =&gt;的 StringPart1 ... <强> StringPart2

HTML:

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

Angular Code:

 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 / hous ... 3720DF6680E17036.jar

答案 14 :(得分: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;
    }

答案 15 :(得分: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',[])

答案 16 :(得分:1)

您可以使用此npm模块:https://github.com/sparkalow/angular-truncate

将截断滤镜注入您的app模块,如下所示:

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

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

{{ text | characters:20 }} 

答案 17 :(得分:1)

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

并希望将数据显示为名称后面的目录,假设&#39; / root&#39;作为目录和&#39;机器&#39;作为名称(/ root-machine)。

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

答案 18 :(得分:1)

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

答案 19 :(得分:0)

最易用的解决方案 - &gt;我发现是让Material Design(1.0.0-rc4)完成这项工作。 md-input-container将为您完成工作。它汇总字符串并添加elipses加上它具有额外的优势,允许您单击它以获取全文,因此它是整个辣酱玉米饼馅。您可能需要设置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
}

答案 20 :(得分:0)

使用自定义角度过滤器限制单词数量: 以下是我使用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

答案 21 :(得分:0)

此解决方案纯粹在HTML上使用 ng 标记。

解决方案是限制显示的长文本,并显示更多...&#39;链接在它的末尾。如果用户点击“显示更多...&#39;链接,它会显示文本的其余部分并删除“显示更多...&#39;链接。

<强> 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>

答案 22 :(得分:0)

它适用于我  '在span',ng-show =“MyCtrl.value。$ viewValue.length&gt; your_limit”...阅读更多。 'end span'

答案 23 :(得分: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: ')';
}

答案 24 :(得分:0)

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

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

用法是:

text | truncate: [length]: [suffix]: [preserve-boolean]

答案 25 :(得分:0)

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

<div>{{ modal.title.length > 20 ? (modal.title | limitTo : 20) + '...' : modal.title }}</div>