programing tip

다른 html이없는 angularjs 개행 필터

itbloger 2020. 9. 15. 07:28
반응형

다른 html이없는 angularjs 개행 필터


개행 문자 ( \n)를 html 로 변환하려고합니다 br. Google 그룹의이 토론에
따라 다음과 같은 내용 이 있습니다.

myApp.filter('newlines', function () {
    return function(text) {
        return text.replace(/\n/g, '<br/>');
    }
});

이 토론에서는보기에서 다음을 사용하는 것이 좋습니다.

{{ dataFromModel | newline | html }}

이것은 이전 html필터를 사용하는 것처럼 보이지만 이제는 ng-bind-html속성 을 사용해야 합니다.


그럼에도 불구하고 이것은 문제를 제기합니다. 원본 문자열 ( dataFromModel)의 HTML이 HTML로 렌더링되는 것을 원하지 않습니다 . br.

예를 들어 다음 문자열이 주어집니다.

7> 5
나는 여전히 여기에 html 및 물건을 원하지 않습니다 ...

출력하고 싶습니다.

While 7 &gt; 5<br>I still don't want html &amp; stuff in here...

이를 수행 할 방법이 있습니까?


어쩌면 html로만 이것을 달성 할 수 <preformated text>있습니까? 필터 사용을 피하거나 모든 종류의 처리를 수행합니다.

이 CSS가있는 요소 내에 텍스트를 표시하기 만하면됩니다.

<p style="white-space: pre;">{{ MyMultiLineText}}</p>

이것은 구문 분석하고 \ n을 새 줄로 표시합니다. 나를 위해 잘 작동합니다.

여기에 jsFiddle 예제가 있습니다.


새로운 지시문을 엉망으로 만드는 대신 2 개의 필터를 사용하기로 결정했습니다.

App.filter('newlines', function () {
    return function(text) {
        return text.replace(/\n/g, '<br/>');
    }
})
.filter('noHTML', function () {
    return function(text) {
        return text
                .replace(/&/g, '&amp;')
                .replace(/>/g, '&gt;')
                .replace(/</g, '&lt;');
    }
});

그런 다음 내 견해로는 하나를 다른 것으로 파이프합니다.

<span ng-bind-html-unsafe="dataFromModel | noHTML | newlines"></span>

이를 수행하는 더 간단한 방법은 각 텍스트를 \n목록으로 분할하는 필터를 만든 다음`ng-repeat를 사용하는 것입니다.

필터 :

App.filter('newlines', function() {
  return function(text) {
    return text.split(/\n/g);
  };
});

그리고 html에서 :

<span ng-repeat="line in (text | newlines) track by $index">
    <p> {{line}}</p>
    <br>
</span>

끝없는 문자열로 레이아웃을 파괴하지 않으려면 pre-line을 사용하십시오.

<p style="white-space: pre-line;">{{ MyMultiLineText}}</p>

I'm not aware if Angular has a service to strip html, but it seems you need to remove html before passing your newlines custom filter. The way I would do it is through a custom no-html directive, which would be passed a scope property and the name of a filter to apply after removing the html

<div no-html="data" post-filter="newlines"></div>

Here's the implementation

app.directive('noHtml', function($filter){
  return function(scope, element, attrs){
    var html = scope[attrs.noHtml];
    var text = angular.element("<div>").html(html).text();

    // post filter
    var filter = attrs.postFilter;
    var result = $filter(filter)(text);

    // apending html
    element.html(result);
  };
});

The important bit is the text variable. Here I create an intermediate DOM element and append it the HTML using the html method and then retrieve only the text with the text method. Both methods are provided by Angular's lite version of jQuery.

The following part is applying the newline filter, which is done using the $filter service.

Check the plunker here: http://plnkr.co/edit/SEtHH5eUgFEtC92Czq7T?p=preview


An update to the filter with ng-bind-html currently would be:

myApp.filter('newlines', function () {
  return function(text) {
    return text.replace(/(&#13;)?&#10;/g, '<br/>');
  }
});

and the noHTML filter is no longer required.

white-space solution is having low browser support: http://caniuse.com/#search=tab-size


Bit late to the party on this but I would suggest a small improvement to check for undefined / null strings.

Something like:

.filter('newlines', function () {
    return function(text) {
        return (text) ? text.replace(/(&#13;)?&#10;/g, '<br/>') : text;
    };
})

Or (bit tighter)

.filter('newlines', function () {
    return function(text) {
        return (text instanceof String || typeof text === "string") ? text.replace(/(&#13;)?&#10;/g, '<br/>') : text;
    };
})

참고URL : https://stackoverflow.com/questions/13964735/angularjs-newline-filter-with-no-other-html

반응형