จำกัดความยาวของสตริงด้วย AngularJS


225

ฉันมีดังต่อไปนี้:

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

มีวิธีที่ฉันสามารถจำกัดความยาวของสายอักขระที่จะพูด 20 ตัวอักษร?

และคำถามที่ดียิ่งขึ้นก็คือมีวิธีที่ฉันสามารถเปลี่ยนสตริงให้ถูกตัดทอนและแสดง...ในตอนท้ายถ้ามันมีมากกว่า 20 ตัวอักษร?


คำตอบ:


344

แก้ไข รุ่นล่าสุดของ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 (บูลีน) - หากเป็นจริงให้ตัดโดยใช้คำ จำกัด
  • สูงสุด (จำนวนเต็ม) - ความยาวสูงสุดของข้อความตัดเป็นจำนวนตัวอักษรนี้
  • tail (สตริงเริ่มต้น: '…') - เพิ่มสตริงนี้ลงในสตริงอินพุตหากสตริงถูกตัด

โซลูชันอื่น : http://ngmodules.org/modules/angularjs-truncate (โดย @Ehvince)


2
มีค่าเท่ากันที่โมดูลเชิงมุม: ngmodules.org/modules/angularjs-truncate
Ehvince

angularjs-truncate ไม่ใช่ทางออก แต่เป็นโซลูชัน IS ของคุณ ขอบคุณ! ทำให้เป็นโมดูล!
Anton Bessonov

@epokk มีวิธีให้ผู้ใช้หลังจากคลิกสามจุดแสดงข้อความเจียระไนสมบูรณ์หรือไม่ ชอบ "แสดงเพิ่มเติม" หรือไม่ ขอบคุณ!
Thales P

สิ่งนี้ใช้ได้ดีเมื่อเราใช้มันเช่นนี้ {{post.post_content | ตัด: จริง: 100: '... '}} แต่ล้มเหลวเมื่อฉันใช้เช่นนี้ <span ng-bind-html = "TrustedHtml (post.post_content | ตัด: จริง: 100: '... ')"> < / span> เพราะฉันถูกบังคับให้ใช้กับ html ที่เชื่อถือได้ในกรณีของฉัน
S Vinesh

ขีด จำกัด ของ wordwise เป็นคุณสมบัติที่ดีที่ดูเหมือนไม่มีอยู่ในค่าเริ่มต้น "limitTo"
pdizz

496

นี่คือการแก้ไขหนึ่งบรรทัดแบบง่ายโดยไม่ต้อง css

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

79
เรียบง่ายและสง่างาม แทนที่จะเป็นเช่น'...'นั้นคุณสามารถใช้เอนทิตี HTML สำหรับจุดไข่ปลา:'&hellip;'
Tom Harrison

อาจเป็นทางออกที่เจ็บปวดที่สุด โปรดทราบว่าตัวกรองค่อนข้างหนักและอาจมีปัญหาเรื่องประสิทธิภาพในรายการซ้ำจำนวนมาก! :)
Cowwando

1
! น่ากลัว มีวิธีการตัดตามจำนวนบรรทัดมากกว่าหลังจากจำนวนอักขระหรือไม่
axd

@axd คุณต้องลองใช้ css หรือเขียนคำสั่งเพื่อให้บรรลุ
Govan

1
นี่คือคำตอบที่ดีที่สุด ผลการดำเนินงานที่ควรมีเล็กน้อยกับจำนวนซ้ำ ng ที่เหมาะสม หากคุณนำเนื้อหาซ้ำหลายร้อยรายการที่ต้องตัดทอนอาจต้องกลับไปที่กระดานวาดรูป คำตอบที่ดี @Govan
erier

59

ฉันรู้ว่ามันสายไปแล้ว แต่ในรุ่นล่าสุดของ angularjs (ฉันใช้ 1.2.16) limitTo filter รองรับสตริงและอาร์เรย์ดังนั้นคุณจึงสามารถจำกัดความยาวของสตริงได้ดังนี้

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

ซึ่งจะส่งออก:

My String

9
วิธีนี้ไม่มี "... " ผลลัพธ์ควรเป็น: "My String ... "
Snæbjørn

ฉันไม่เห็นจุดไข่ปลาที่นี่: plnkr.co/edit/HyAejS2DY781bqcT0RgV?p=preview คุณสามารถทำอย่างละเอียด?
บาง

2
สิ่งที่ @ Snæbjørnกำลังพูดคือคนที่ถามคำถามนั้นต้องการวิธีการแก้ปัญหาที่แทรก "... " ที่ส่วนท้ายของสตริงที่ถูกตัดทอน คำตอบของโกแวนทำเช่นนั้น
nahn

@ Nahn ขอบคุณสำหรับการชี้ให้เห็นว่า ฉันน่าจะแสดงความคิดเห็นกับคำตอบของ EpokK แทนคำตอบอื่น
บาง

52

คุณสามารถเพิ่มคลาส 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
ข้อความล้น: จุดไข่ปลาดี
Chris Russo

4
เทคนิคนี้ในขณะที่ยอดเยี่ยมป้องกันข้อความจากการตัด
Larry

นี่คือคำตอบที่ถูกต้อง กฎทั่วไปของฉันคือ: "อย่าทำใน JavaScript ซึ่งสามารถทำได้ใน CSS"
Aidan

4
ใช้งานได้กับข้อความที่มีหนึ่งบรรทัดต่อย่อหน้าเท่านั้น ดู multiline css-tricks.com/line-clampin (ไม่ใช่ทุกเบราว์เซอร์ที่รองรับ)
Robert

วิธีนี้จะใช้งานได้หากคุณพยายามจำกัดความยาวของอาเรng-repeatย์
chakeda

27

ฉันมีปัญหาที่คล้ายกันนี่คือสิ่งที่ฉันทำ:

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

ฉันจะลบช่องว่างระหว่างผลลัพธ์ทั้งสองเพื่อหลีกเลี่ยงการขึ้นบรรทัดใหม่
อิกนาชิโอวาซิเกซ

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

วิธีการที่ง่ายที่สุด แต่ยังใช้งานได้ แต่สันนิษฐานว่าทุกชื่อจะมีมากกว่า 20 ตัวอักษรและในบางกรณีอาจไม่คาดคิด
Henrique M.

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


ฉันขอแนะนำให้เพิ่มผลตอบแทนในกรณีที่inputค่าเป็นแบบไดนามิกหรือไม่ ie if (!input) {return;}มิฉะนั้นจะมีข้อผิดพลาดคอนโซล JS
mcranston18

1
@ mcranston18 เพิ่มแล้ว ขอบคุณ.
Anam

15

เนื่องจากเราต้องการจุดไข่ปลาเฉพาะเมื่อความยาวของสายอักขระเกินขีด จำกัด จึงควรเพิ่มจุดไข่ปลาโดยการใช้ng-ifมากกว่าการผูก

{{ longString | limitTo: 20 }}<span ng-if="longString.length > 20">&hellip;</span>

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>


7

ทางออกที่ง่ายที่สุดที่ฉันพบเพียงจำกัดความยาวของสตริงคือ{{ 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


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...");
    });
});

3

คุณสามารถจำกัดความยาวของสตริงหรืออาร์เรย์ได้โดยใช้ตัวกรอง ตรวจสอบสิ่งนี้เขียนโดยทีม AngularJS


ให้รายละเอียดเพิ่มเติมด้วย
Parixit

3

ใน html ใช้ของตนพร้อมกับตัวกรอง 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;

        }


    }

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) ;
   };
}]);

ตัวอย่างที่มีพารามิเตอร์ต่อไปนี้:
startLimit = 10
endLimit = 20

ก่อนหน้า : - /home/house/room/etc/ava_B0363852D549079E3720DF6680E17036.jar
หลังจาก : - /home/hous...3720DF6680E17036.jar


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',[])

2

สิ่งนี้อาจไม่ได้มาจากท้ายสคริปต์ แต่คุณสามารถใช้ css ด้านล่างและเพิ่มคลาสนี้ให้กับ div สิ่งนี้จะตัดทอนข้อความและแสดงข้อความแบบเต็มเมื่อวางเมาส์ คุณสามารถเพิ่มข้อความเพิ่มเติมและเพิ่ม Hadler คลิกเชิงมุมเพื่อเปลี่ยนคลาสของ div ใน cli

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

    .ellipseContent:hover {
        overflow: visible;
        white-space: normal;
    }

2

หากคุณมีสองผูกและ{{item.name}}{{item.directory}}

และต้องการแสดงข้อมูลเป็นไดเรกทอรีตามด้วยชื่อสมมติว่า '/ root' เป็นไดเรกทอรีและ 'Machine' เป็นชื่อ (/ root-machine)

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

มีโอกาสที่คุณโพสต์คำตอบนี้ในคำถามที่ผิดหรือไม่? สิ่งนี้ดูเหมือนจะไม่เกี่ยวข้องกับการจำกัดความยาวของสตริงด้วย AngularJS
BSMP



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: ')';
}

0

โซลูชันนี้ใช้แท็กngกับ HTML เท่านั้น

วิธีแก้ไขคือ จำกัด ข้อความที่มีความยาวที่แสดงพร้อมกับลิงก์ 'แสดงเพิ่มเติม ... ' ที่ท้ายข้อความ หากผู้ใช้คลิกที่ลิงค์ 'แสดงเพิ่มเติม ... ' มันจะแสดงข้อความที่เหลือและลบลิงก์ 'แสดงเพิ่มเติม ... '

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>

0

ทางออกที่ง่ายที่สุด -> ฉันได้พบคือให้การออกแบบวัสดุ (1.0.0-rc4) ทำงาน md-input-containerจะทำงานให้คุณ มันเชื่อมต่อสตริงและเพิ่ม elipses บวกมันมีข้อได้เปรียบพิเศษของการอนุญาตให้คุณคลิกเพื่อรับข้อความเต็มจึงเป็น enchilada ทั้งหมด 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
}

0

จำกัด จำนวนคำด้วยตัวกรองเชิงมุมที่กำหนดเอง: นี่คือวิธีที่ฉันใช้ตัวกรองเชิงมุมเพื่อ จำกัด จำนวนคำที่แสดงโดยใช้ตัวกรองแบบกำหนดเอง

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

0

มันทำงานได้ดีสำหรับฉัน 'In span', ng-show = "MyCtrl.value. $ viewValue.length> your_limit" ... อ่านเพิ่มเติม 'สิ้นสุดช่วง'


0

ฉันใช้ไลบรารี่ตัวกรองที่มีประโยชน์ "Angular-filter" และหนึ่งในนั้นที่เรียกว่า "truncate" ก็มีประโยชน์เช่นกัน

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

การใช้งานคือ:

text | truncate: [length]: [suffix]: [preserve-boolean]
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.