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.
Internally the AngularJS sanitzer uses a encodeEntities function, but does not expose it. I know I could duplicate the function, but it seems like there should be a standard way of doing this.
Use-Case: I have a custom directive which does language localization. This directive uses a key lookup from a data file to find language text. In some cases this text is allowed to contain HTML, and/or the directive produces HTML to improve the resulting visual formatting. In addition this directive takes Angular expressions as parameters and uses them as replacements for tokens in the strings. I need to encode these parameters as they may not be HTML safe.
The directive is called as an attribute, for example i18n-html='welcome_text_html,1+1,user.name'
. The directive then formats the string as described and uses element.html
to update the DOM node.
Angular automatically escapes data if you use ng-bind or the {{ curly brace syntax }} . This means it outputs the literal characters instead of interpreting them as HTML.
Escaping in HTML means, that you are replacing some special characters with others. In HTML it means usally, you replace e. e.g < or > or " or & . These characters have special meanings in HTML. Imagine, you write <b>hello, world</b> And the text will appear as hello, world.
The $ in AngularJs is a built-in object.It contains application data and methods.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With