html 대신 일반 텍스트를 출력하는 angularjs
다음과 같은 문자가 있습니다.
<span>My text</span>
태그 없이 표시:
My text
태그도 붙이고 싶지 않고 벗기고 싶어요.어떻게 하면 쉽게 할 수 있을까요?
각도 html:
<div>{{myText | htmlToPlaintext}}</div>
jQuery는 약 40배 느립니다. 이 간단한 작업에는 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.displicate(각선).
raw 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>
이를 위해 regexp를 적용하는 대신 내장 브라우저 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;
}());
자체 실행 함수로 래핑하는 이유는 요소 생성을 재사용하기 위해서입니다.
<div ng-bind-html="myText"></div>
{{myText}}처럼 html {{}}개의 보간 태그에 넣을 필요가 없습니다.
모듈 내에서 ngSanitize를 사용하는 것을 잊지 마십시오. var app = angular.module("myApp", ['ngSanitize']);
https://cdnjs.com/libraries/angular-sanitize 페이지에 cdn 의존관계를 추가합니다.
ng-bind-html을 사용할 수 있습니다.모듈에 $sanitize 서비스를 삽입하는 것을 잊지 마십시오.이것이 도움이 되기를 바랍니다.
ng-bind-html을 사용하는 것은 적절하고 간단한 방법입니다.
이 기능을 다음과 같이 사용합니다.
String.prototype.text=function(){
return this ? String(this).replace(/<[^>]+>/gm, '') : '';
}
"<span>My text</span>".text()
output:
My text
언급URL : https://stackoverflow.com/questions/17289448/angularjs-to-output-plain-text-instead-of-html
'programing' 카테고리의 다른 글
componentWillReceiveProps에서 변경된 소품을 확인하는 방법 (0) | 2023.03.19 |
---|---|
mysql CLI는 연결할 수 있지만 WordPress는 연결할 수 없는 이유는 무엇입니까? (0) | 2023.03.19 |
DD/MM/YYY 날짜 형식(Moment.js) (0) | 2023.03.19 |
반응 - 순수 상태 비저장 구성 요소를 내보내는 방법 (0) | 2023.03.19 |
OnClick은 작동하지만 React 구성 요소에서는 OnDoubleClick이 무시됨 (0) | 2023.03.19 |