Ogranicz Długość łańcucha za pomocą AngularJS

Mam następujące:

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

Czy jest sposób, aby ograniczyć długość łańcucha do 20 znaków?

A jeszcze lepszym pytaniem byłoby to, czy jest sposób, aby zmienić łańcuch, aby został ścięty i pokazać ... na końcu, jeśli ma więcej niż 20 znaków?

Author: Andrew Sula, 2013-08-07

24 answers

Edytuj Najnowsza wersja AngularJS oferuje limitTo Filtr .

Potrzebujesz niestandardowego filtra w ten sposób:

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

Użycie:

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

Opcje:

  • wordwise (boolean) - jeśli jest to prawda, wyciąć tylko przez granice słów,
  • max (integer) - maksymalna długość tekstu, przycinana do tej liczby znaków,
  • tail (string, domyślnie:'...') - dodaj ten łańcuch do wejścia ciąg, jeśli ciąg został przecięty.

Inny rozwiązanie: http://ngmodules.org/modules/angularjs-truncate (by @ Ehvince)

 336
Author: EpokK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-06 12:41:16

Oto prosta poprawka jednej linii bez css.

{{ myString | limitTo: 20 }}{{myString.length > 20 ? '...' : ''}}
 480
Author: Govan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-17 13:49:26

Wiem, że jest późno, ale w najnowszej wersji angularjs (używam 1.2.16) filtr limitTo obsługuje zarówno łańcuchy, jak i tablice, więc możesz ograniczyć długość łańcucha w następujący sposób:

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

Który wyświetli:

My String
 57
Author: slim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-09 14:42:17

Możesz po prostu dodać klasę css do div I dodać podpowiedź za pomocą angularjs, aby przycięty tekst był widoczny po najechaniu myszą.

<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;
   }
 50
Author: Sushrut,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-07 06:42:51

Miałem podobny problem, Oto co zrobiłem:

{{ longString | limitTo: 20 }} {{longString.length < 20 ? '' : '...'}}
 27
Author: crc442,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-10 18:59:05

Bardziej eleganckie rozwiązanie:

HTML:

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

Kod Kątowy:

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

Demo:

Http://code-chunk.com/chunks/547bfb3f15aa1/str-limit-implementation-for-angularjs

 17
Author: Anam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-25 23:03:25

Ponieważ potrzebujemy elipsy tylko wtedy, gdy długość łańcucha przekracza limit, bardziej odpowiednie wydaje się dodanie elipsy za pomocą ng-if niż wiązania.

{{ longString | limitTo: 20 }}<span ng-if="longString.length > 20">&hellip;</span>
 15
Author: mnishiguchi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-12 21:11:28
< div >{{modal.title | limitTo:20}}...< / div>
 13
Author: Thiago Araújo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-15 07:38:47

Istnieje opcja

.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>
 6
Author: Aleksandr Havrylov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-29 09:49:37

Oto własny filtr do obcinania tekstu. Jest inspirowany rozwiązaniem epok, ale zmodyfikowany pod moje potrzeby i gusta.

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

A oto testy jednostkowe, dzięki którym możecie zobaczyć jak ma się zachowywać:

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...");
    });
});
 4
Author: SharkAlley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-01 08:59:02

Możesz ograniczyć długość łańcucha lub tablicy za pomocą filtra. Sprawdź Ten napisany przez zespół AngularJS.

 3
Author: MAM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-12 06:24:00

w html używany wraz z filtrem limitTo dostarczonym przez angular jak poniżej,

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

        }


    }
 3
Author: Shushanth Pallegar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-01 11:53:35

Jeśli chcesz coś w stylu: InputString => StringPart1 ...StringPart2

HTML:

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

Kod Kątowy:

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

Przykład z następującymi parametrami :
beginLimit = 10
endLimit = 20

Przed : - /home/house/room/etc/ava_B0363852D549079E3720DF6680E17036.jar
Po : - /home / hous...3720DF6680E17036jar

 3
Author: vhamon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-05 13:21:40

Najprostszym rozwiązaniem, które znalazłem na proste ograniczenie długości struny, było {{ modal.title | slice:0:20 }}, a następnie zapożyczenie z @Govan powyżej można użyć {{ modal.title.length > 20 ? '...' : ''}}, aby dodać punkty zawieszenia, jeśli struna jest dłuższa niż 20, więc końcowy wynik jest po prostu:

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

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

 3
Author: maudulus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-05 21:36:38
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
Author: Mohideen ibn Mohammed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-08 12:55:38

To może nie być z końca skryptu, ale możesz użyć poniższego css i dodać tę klasę do div. Spowoduje to obcięcie tekstu, a także wyświetlenie pełnego tekstu na mouseover. Możesz dodać więcej tekstu i dodać kątowe kliknięcie hadlera, aby zmienić klasę div na cli

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

    .ellipseContent:hover {
        overflow: visible;
        white-space: normal;
    }
 2
Author: Kurkula,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-11 19:23:11

Możesz użyć tego modułu npm: https://github.com/sparkalow/angular-truncate

Wprowadź filtr truncate do modułu aplikacji w następujący sposób:

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

I zastosuj filtr w aplikacji w ten sposób:

{{ text | characters:20 }} 
 1
Author: charming mel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-26 14:11:14

Najprostszym rozwiązaniem -- > znalazłem jest pozwolić Material Design (1.0.0-rc4) wykonać pracę. md-input-container zrobi to za Ciebie. Łączy ciąg i dodaje elipsy plus ma dodatkową zaletę, pozwalając kliknąć go, aby uzyskać pełny tekst, więc jest to cała enchilada. Może być konieczne ustawienie szerokości 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
}
 1
Author: Helzgate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-16 16:30:30

Jeśli masz dwa wiązania {{item.name}} i {{item.directory}}.

I chcesz pokazać dane jako katalog, po którym następuje nazwa, zakładając "/ root "jako katalog i "Machine" jako nazwę (/root-machine).

{{[item.directory]+[isLast ? '': '/'] + [ item.name]  | limitTo:5}}
 1
Author: Harish Pothula,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-16 23:06:14

StworzyĹ 'em dyrektywÄ™, ktĂłra Ĺ' atwo to robi, obcinaĺ ' a napis do okreĹ "lonego limitu i dodaje przeĹ 'Ä ... cznik" Pokaż wiÄ ™ cej/mniej". Możesz go znaleźć na Githubie: https://github.com/doukasd/AngularJS-Components

Można go używać w następujący sposób:

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

Oto dyrektywa:

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

I jakiś CSS do tego:

.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
Author: Dimitris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-07 14:52:55

To rozwiązanie jest wyłącznie za pomocą ng tag w HTML.

Rozwiązaniem jest ograniczenie wyświetlania długiego tekstu za pomocą ' Pokaż więcej... link na końcu. Jeśli użytkownik kliknie ' Pokaż więcej...'link, pokaże resztę tekstu i usunięte' Pokaż więcej..."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>
 0
Author: Amirul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-17 10:59:55

Ogranicz liczbę słów za pomocą niestandardowego filtra kątowego: Oto jak użyłem filtra kątowego, aby ograniczyć liczbę słów wyświetlanych za pomocą niestandardowego filtra.

HTML:

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

Kod Kątowy / 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
Author: Geoff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-01 18:52:26

Dla mnie Działa ok "In span", ng-show = " MyCtrl.wartość.$viewValue.długość > your_limit"...Czytaj więcej. "end span"

 0
Author: G. K.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-12 05:33:31

Używam ładnego zestawu przydatnych bibliotek filtrów "Angular-filter" i jedna z nich o nazwie "truncate" jest również przydatna.

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

Użycie to:

text | truncate: [length]: [suffix]: [preserve-boolean]
 0
Author: Lukas Jelinek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-29 09:28:00