Is there an angular JS command that will do HTML escaping on text? I am processing a custom directive and have need to escape some of the output which it generates.
This answer is about escaping, not sanitizing HTML. There are two approaches:
As mentioned by @maniekq, if you can work on the DOM, do:
element.text( scope.myValue );
From this answer, you can use this code from mustache.js and e.g. create an angular filter:
angular.module('myModule').filter('escapeHtml', function () {
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
return function(str) {
return String(str).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
});
Sanitizing is one thing, but to display all characters and not "execute" HTML code I have used "text" function to set value.
In your directive, to set value, instead of writing:
element.html( scope.myValue );
write:
element.text( scope.myValue );
You can implement filter like this:
app.filter('escape', escape);
function escape() {
return function (html) {
return angular.element('<pre/>').text(html).html();
};
}