IT박스

HTML 대신 일반 텍스트를 출력하는 angularjs

itboxs 2020. 11. 19. 07:58
반응형

HTML 대신 일반 텍스트를 출력하는 angularjs


다음과 같은 텍스트가 있습니다.

<span>My text</span>

태그없이 표시하고 싶습니다.

My text

또한 태그를 적용하고 싶지 않고 제거하고 싶습니다. 그렇게하는 쉬운 방법은 무엇입니까?

각도 HTML :

<div>{{myText | htmlToPlaintext}}</div>

jQuery는 약 40 배 SLOWER 입니다. 간단한 작업에는 jQuery를 사용하지 마십시오.

function htmlToPlaintext(text) {
  return text ? String(text).replace(/<[^>]+>/gm, '') : '';
}

사용법 :

var plain_text = htmlToPlaintext( your_html );

angular.js 사용 :

angular.module('myApp.filters', []).
  filter('htmlToPlaintext', function() {
    return function(text) {
      return  text ? String(text).replace(/<[^>]+>/gm, '') : '';
    };
  }
);

사용하다 :

<div>{{myText | htmlToPlaintext}}</div>  

에서 https://docs.angularjs.org/api/ng/function/angular.element

angular.element

원시 DOM 요소 또는 HTML 문자열을 jQuery 요소로 래핑합니다 (jQuery를 사용할 수없는 경우 angular.element는 "jQuery lite"또는 "jqLite"라고하는 Angular의 기본 제공 jQuery 하위 집합에 위임).

따라서 간단하게 다음을 수행 할 수 있습니다.

angular.module('myApp.filters', []).
  filter('htmlToPlaintext', function() {
    return function(text) {
      return angular.element(text).text();
    }
  }
);

용법:

<div>{{myText | htmlToPlaintext}}</div>

var app = angular.module('myapp', []);

app.filter('htmlToPlaintext', function()
{
    return function(text)
    {
        return  text ? String(text).replace(/<[^>]+>/gm, '') : '';
    };
});

<p>{{DetailblogList.description | htmlToPlaintext}}</p>

자신에게 정규 표현식을 적용하는 대신 내장 브라우저 HTML 스트립을 사용하고 싶습니다. 녹색 브라우저가 당신을 위해 일하기 때문에 더 안전합니다.

angular.module('myApp.filters', []).
  filter('htmlToPlaintext', function() {
    return function(text) {
      return stripHtml(text);
    };
  }
);

var stripHtml = (function () {
  var tmpEl = $document[0].createElement("DIV");
  function strip(html) {
    if (!html) {
      return "";
    }
    tmpEl.innerHTML = html;
    return tmpEl.textContent || tmpEl.innerText || "";
  }
  return strip;
}());

The reason for wrapping it in an self-executing function is for reusing the element creation.


<div ng-bind-html="myText"></div> No need to put into html {{}} interpolation tags like you did {{myText}}.

and don't forget to use ngSanitize in module like e.g. var app = angular.module("myApp", ['ngSanitize']);

and add its cdn dependency in index.html page https://cdnjs.com/libraries/angular-sanitize


You can use ng-bind-html, don't forget to inject $sanitize service into your module Hope it helps


Use ng-bind-html this is only proper and simplest way


Use this function like

 String.prototype.text=function(){
   return this ? String(this).replace(/<[^>]+>/gm, '') : '';
 }

  "<span>My text</span>".text()
  output:
  My text

Fiddle

참고URL : https://stackoverflow.com/questions/17289448/angularjs-to-output-plain-text-instead-of-html

반응형