I have some text like this:
<span>My text</span>
I want to display without tags:
My text
I also don't want to apply the tags, I want to strip them. What's an easy way to do that?
Angular html:
<div>{{myText | htmlToPlaintext}}</div>
This question is related to
javascript
html
angularjs
from https://docs.angularjs.org/api/ng/function/angular.element
angular.element
wraps a raw DOM element or HTML string as a jQuery element (If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite.")
So you simply could do:
angular.module('myApp.filters', []).
filter('htmlToPlaintext', function() {
return function(text) {
return angular.element(text).text();
}
}
);
Usage:
<div>{{myText | htmlToPlaintext}}</div>
You want to use the built-in browser HTML strip for that instead of applying yourself a regexp. It is more secure since the ever green browser does the work for you.
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.
You can use ng-bind-html, don't forget to inject $sanitize service into your module Hope it helps
<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
var app = angular.module('myapp', []);
app.filter('htmlToPlaintext', function()
{
return function(text)
{
return text ? String(text).replace(/<[^>]+>/gm, '') : '';
};
});
<p>{{DetailblogList.description | htmlToPlaintext}}</p>
Use this function like
String.prototype.text=function(){
return this ? String(this).replace(/<[^>]+>/gm, '') : '';
}
"<span>My text</span>".text()
output:
My text
Use ng-bind-html this is only proper and simplest way
Source: Stackoverflow.com