2

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?

Tekill
  • 1,171
  • 1
  • 14
  • 30
  • 1
    Are you appending this text to an SVG? – Gerardo Furtado Aug 15 '16 at 15:04
  • yes sir! @GerardoFurtado I think I know where you are going there, the svg can't interpret the html? I used the replace function in the string to replace the &amp#39; and & and that works but is there a more elegant solution? – Tekill Aug 15 '16 at 15:10
  • 1
    I was right now writing an answer... you cant use HTML entities in SVG. Can you change them to unicode? Or are you getting the text as a string with the HTML entities in it? – Gerardo Furtado Aug 15 '16 at 15:11
  • Is there a pre-established javascript function for that? Go ahead and write your answer, I def had not thought about the fact it was an SVG – Tekill Aug 15 '16 at 15:13

1 Answers1

2

The problem is that, right now, you are trying to use an HTML entity in the SVG text element, 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.

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171