簡體   English   中英

angularjs輸出純文本而不是html

[英]angularjs to output plain text instead of html

我有這樣的文字:

<span>My text</span>

我想顯示沒有標簽:

My text

我也不想應用標簽,我想剝離它們。 有什么簡單的方法可以做到這一點?

Angular html:

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

jQuery大約是SLOWER的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.element

將原始DOM元素或HTML字符串包裝為jQuery元素(如果jQuery不可用,angular.element委托給Angular的內置jQuery子集,稱為“jQuery lite”或“jqLit​​e。”)

所以你可以做到:

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

將其包裝在自執行函數中的原因是為了重用元素創建。

<div ng-bind-html="myText"></div>無需像{{myText}}一樣放入html {{}}插值標簽。

並且不要忘記在模塊中使用ngSanitize,例如var app = angular.module("myApp", ['ngSanitize']);

並在index.html頁面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

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM