Yourinium Yourinium - 3 months ago 15
AngularJS Question

untrusted HTML in d3.js v4 and AngularJS

I am having issue with special character not being displayed properly, I am generating a d3.js tree layout diagram via an angular JS directive, text is being added into the diagram by the directive but any special character is not displayed properly, instead of apostrophe I get ' and & instead of & etc... I have tried the use of a filter

$filter('html')(d.name)
with no luck

app.filter('html',function($sce){
return function(input){
var value = input.toString();
console.log(input);
var output = $sce.trustAsHtml(value);
console.log(output);
return output;
}
});


I also tried the following:

nodeEnter.append("text")
.attr("dy", 3)
.attr("x", 1e-6)

.attr("compile-template","")
.attr("ng-bind-html", function(d) {
var output = $sce.trustAsHtml(d.name);
return output;
})


OR

nodeEnter.append("text")
.attr("dy", 3)
.attr("x", 1e-6)
.text(function(d) {
var output = $sce.trustAsHtml(d.name);
return output;
})


Both without luck, is there any other way to get special characters to display through my directive?

Answer

The problem is that, right now, you are trying to append an HTML entity to the SVG, and this won't work.

The first solution is just changing the HTML entity for the proper Unicode. For instance, to show an ampersand, instead of:

.text("&")

or

.text("&")

You should do:

.text("\u0026")

Check the snippet:

var svg = d3.select("body")
    .append("svg")
    .attr("width", 400)
    .attr("height", 200);
	
svg.append("text")
    .attr("x", 10)
    .attr("y", 20)
    .text("This is an ampersand with HTML entity:  & (not good)");

svg.append("text")
    .attr("x", 10)
    .attr("y", 50)
    .text("This is an ampersand with Unicode: \u0026 (perfect)");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

The second solution involves using the HTML entities without changing them. If changing all your HTML entities to Unicode is not an option to you, you can append an foreign object, which accepts HTML entities.

Comments