untrusted HTML in d3.js v4 and AngularJS

坚强是说给别人听的谎言 提交于 2019-12-12 18:19:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/38956615/untrusted-html-in-d3-js-v4-and-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!