Programing

angularjs에서 줄 바꿈 유지

crosscheck 2020. 5. 26. 19:41
반응형

angularjs에서 줄 바꿈 유지


나는 SO 질문 을 보았습니다 .

이전 버전 이 있기 때문에 코드 대신 ng-bind="item.desc"사용합니다 .{{item.desc}}ng-repeat

그래서 내 코드 :

<div ng-repeat="item in items">
  {{item.description}}
</div>

항목 설명 \n에 줄 바꿈이 포함되어 있지 않습니다.

{{item.description}}ng-repeat내용 이 있다고 가정하면 개행을 쉽게 표시 할 수 있습니까?


@pilau의 답변을 기반으로하지만 허용 된 답변조차도 개선하지 못했습니다.

<div class="angular-with-newlines" ng-repeat="item in items">
   {{item.description}}
</div>

/* in the css file or in a style block */
.angular-with-newlines {
    white-space: pre-wrap;
}

주어진 줄 바꿈과 공백을 사용하지만 내용 경계에서 내용을 끊습니다. 공백 속성에 대한 자세한 내용은 다음을 참조하십시오.

https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

줄 바꿈을하고 싶지만 텍스트 앞에있는 여러 공백이나 공백을 축소하려면 (원래 브라우저 동작과 매우 유사) @aaki가 제안한대로 사용할 수 있습니다.

white-space: pre-line;

다양한 렌더링 모드를 잘 비교 한 것 : http://meyerweb.com/eric/css/tests/white-space.html


시험:

<div ng-repeat="item in items">
  <pre>{{item.description}}</pre>
</div>

<pre>래퍼로 텍스트를 인쇄 할 \n텍스트로

또한 json을 인쇄하면 더 나은 모양을 위해 다음 json과 같은 필터를 사용하십시오 .

<div ng-repeat="item in items">
  <pre>{{item.description|json}}</pre>
</div>

Demo

어쨌든 사용 @Paul Weber하는 white-space: pre-wrap;것이 더 나은 방법 이라는 데 동의합니다 <pre>. 스타일을 익히는 데 시간을 낭비하고 싶지 않은 경우 주로 일부 항목을 디버깅하는 빠른 방법


CSS로 너무 간단합니다 (작동합니다, 맹세합니다).

.angular-with-newlines {
  white-space: pre;
}
  • 엄마 봐요! 추가 HTML 태그가 없습니다!

CSS를 사용하면 쉽게 달성 할 수 있습니다.

<div ng-repeat="item in items">
<span style="white-space:pre-wrap;"> {{item.description}}</span>
</div>  

또는 이러한 목적으로 CSS 클래스를 작성하고 외부 CSS 파일에서 사용할 수 있습니다.


글쎄, 그것은 당신이 데이터를 묶고 싶다면, 그 안에 어떤 형식도 없어야합니다. 그렇지 않으면 원하는 것이 무엇인지 확실 bind-html하지 description.replace(/\\n/g, '<br>')않을 수 있습니다 .


CSS 솔루션은 작동하지만 실제로 스타일을 제어 할 수는 없습니다. 필자의 경우 줄 바꿈 후에 약간 더 많은 공간을 원했습니다. 다음은 이것을 처리하기 위해 만든 지시문입니다 (typescript).

function preDirective(): angular.IDirective {
    return {
        restrict: 'C',
        priority: 450,
        link: (scope, el, attr, ctrl) => {
            scope.$watch(
                () => el[0].innerHTML,
                (newVal) => {
                    let lineBreakIndex = newVal.indexOf('\n');
                    if (lineBreakIndex > -1 && lineBreakIndex !== newVal.length - 1 && newVal.substr(lineBreakIndex + 1, 4) != '</p>') {
                        let newHtml = `<p>${replaceAll(el[0].innerHTML, '\n\n', '\n').split('\n').join('</p><p>')}</p>`;
                        el[0].innerHTML = newHtml;
                    }
                }
            )
        }
    };

    function replaceAll(str, find, replace) {
        return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
    }

    function escapeRegExp(str) {
        return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }
}

angular.module('app').directive('pre', preDirective);

사용하다:

<div class="pre">{{item.description}}</div>

텍스트의 각 부분을 <p>태그 로 감싸기 만하면됩니다 . 그런 다음 원하는 스타일을 지정할 수 있습니다.


예,이 중 하나를 사용하는 것이 <pre>태그를 사용하거나 ng-bind-html-unsafe http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe을 사용 후 (사용 겨 바인드 - HTML은 1.2+를 사용하는 경우) .replace()에 변화 /n<br />


Just use the css style "white-space: pre-wrap" and you should be good to go. I've had the same issue where I need to handle error messages for which the line breaks and white spaces are really particular. I just added this inline where I was binding the data and it works like Charm!


I had a similar problem to you. I'm not that keen on the other answers here because they don't really allow you to style the newline behaviour very easily. I'm not sure if you have control over the original data, but the solution I adopted was to switch "items" from being an array of strings to being an array of arrays, where each item in the second array contained a line of text. That way you can do something like:

<div ng-repeat="item in items">
  <p ng-repeat="para in item.description">
     {{para}}
  </p>
</div>

This way you can apply classes to the paragraphs and style them nicely with CSS.


Just add this to your styles, this works for me

white-space: pre-wrap

By this text in <textarea>can be display as it's in there with spaces and line brakes

HTML

   <p class="text-style">{{product?.description}}</p>

CSS

.text-style{
    white-space: pre-wrap
}

참고URL : https://stackoverflow.com/questions/19684708/preserve-line-breaks-in-angularjs

반응형