programing

각도로 문자열 길이 제한JS

elseif 2023. 4. 4. 21:05

각도로 문자열 길이 제한JS

다음과 같은 것이 있습니다.

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

문자열 길이를 20자로 제한할 수 있는 방법이 있나요?

더 수 것 같아요....20달러?

다음은 css를 사용하지 않는 간단한 한 줄 수정입니다.

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

의 최신 버전 편집AngularJS는 필터를 제공합니다.

다음과 같은 커스텀필터가 필요합니다.

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 (구체적) - true일 경우 단어 경계만으로 잘라냅니다.
  • max (최소) - 텍스트의 최대 길이, 이 문자 수로 잘라냅니다.
  • tail(string, default: '...'): 문자열이 잘린 경우 이 문자열을 입력 문자열에 추가합니다.

다른 솔루션: http://ngmodules.org/modules/angularjs-truncate (@Ehvince)

늦은 건 알지만 최신 버전의 angularjs(저는 1.2.16)에서는 limitTo 필터가 문자열과 어레이를 지원하므로 다음과 같이 문자열 길이를 제한할 수 있습니다.

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

출력:

My String

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

저도 같은 문제가 있었습니다.그것은 다음과 같습니다.

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

보다 우아한 솔루션:

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

이 더 것 .ng-if속력하다

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

문자열 길이를 제한하는 가장 간단한 해결책은 다음과 같습니다.{{ modal.title | slice:0:20 }}의 @하면 @Govan을 사용할 수 {{ 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

옵션이 있습니다.

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

여기 텍스트 잘라내기를 위한 사용자 지정 필터가 있습니다.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...");
    });
});

필터를 사용하여 문자열 또는 배열의 길이를 제한할 수 있습니다.Angular에 의해 작성된 이 문서를 확인합니다.JS팀.

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;

        }


    }

InputString = > StringPart1과 같은 것이 필요한 경우...String Part 2

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

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

스크립트 엔드에서 온 것이 아닐 수도 있지만 아래 css를 사용하여 이 클래스를 div에 추가할 수 있습니다.그러면 텍스트가 잘리고 마우스 위에 전체 텍스트가 표시됩니다.더 많은 텍스트를 추가하고 각도 클릭 핸들러를 추가하여 cli에서 div 클래스를 변경할 수 있습니다.

.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}}
<div>{{modal.title | slice: 0: 20}}</div>

다음 npm 모듈을 사용할 수 있습니다.https://github.com/sparkalow/angular-truncate

다음과 같이 잘라내기 필터를 앱 모듈에 삽입합니다.

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

다음과 같이 앱에 필터를 적용합니다.

{{ text | characters:20 }} 

삼원 하여 '나다'로 절사를 ....음음음같 뭇매하다

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

이 디렉티브를 작성했습니다.이 디렉티브는 간단하게, 스트링을 지정된 제한까지 잘라내, 「show more/less」토글을 추가합니다.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: ')';
}

이 솔루션은 순수하게 HTML의 ng 태그를 사용하고 있습니다.

해결책은 끝에 '더 보기...' 링크가 표시된 긴 텍스트를 제한하는 것입니다.사용자가 '더 보기...' 링크를 클릭하면 나머지 텍스트가 표시되고 '더 보기...' 링크가 제거됩니다.

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>

가장 쉬운 해결책은 재료 설계(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
}

사용자 정의 각도 필터를 사용하여 단어 수 제한:다음은 각도 필터를 사용하여 사용자 정의 필터를 사용하여 표시되는 단어 수를 제한한 방법입니다.

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

저는 'In span', ng-show = "MyCtrl.value"로 동작합니다.$viewValue.length > your_limit"...자세한 내용은 이쪽.'엔드 스판'

나는 유용한 필터 라이브러리 "Angular-filter"를 사용했는데, 그 중 "Truncate"라고 불리는 것도 유용하다.

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

사용방법:

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

ng-keypress="filterValue($event)" ng-model="고객.고객_전화"

$scope.filterValue = 함수 이벤트){

        if(isNaN(String.fromCharCode($event.keyCode)) ){
            $event.preventDefault();
        }
        if($scope.customer.CUSTOMER_PHONE.length <= 11)
        {              
            $scope.customer.CUSTOMER_PHONE = $scope.customer.CUSTOMER_PHONE;
        }
        else
        {
            $event.preventDefault();
        }

    };

언급URL : https://stackoverflow.com/questions/18095727/limit-the-length-of-a-string-with-angularjs