javascript - d3.js v4 和 AngularJS 中不受信任的 HTML

标签 javascript angularjs unicode d3.js

我遇到特殊字符无法正确显示的问题,我正在通过 Angular JS 指令生成 d3.js 树布局图,文本正通过指令添加到图中,但任何特殊字符都无法正确显示,我得到的不是撇号而是 '和&而不是 & 等...我尝试使用过滤器 $filter('html')(d.name) 但没有运气

    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;
    }
});

我还尝试了以下方法:

 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;
      })

或者

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

都没有运气,还有其他方法可以通过我的指令显示特殊字符吗?

最佳答案

问题是,现在,您正在尝试使用 HTML entity在 SVG 文本元素中,这是行不通的。

第一个解决方案只是将 HTML 实体更改为正确的 Unicode 。例如,要显示 & 符号,而不是:

.text("&")

.text("&")

你应该这样做:

.text("\u0026")

检查代码片段:

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>

第二个解决方案涉及使用 HTML 实体而不更改它们。如果您无法将所有 HTML 实体更改为 Unicode,则可以附加 foreign object ,它接受 HTML 实体。

关于javascript - d3.js v4 和 AngularJS 中不受信任的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38956615/

相关文章:

javascript - 如何创建将覆盖 ng-disabled 的自定义 Angular Directive(指令)?

haskell - GHC:Unicode 字符的显示

python - 为什么 json.loads 返回一个 unicode 对象而不是字符串

javascript - 为什么 promise 在 setTimeout 之前解决

javascript - 使用 requirejs 全局化和 cldr

javascript - 如何在 AngularJS 中加载内容时添加微调器?

javascript - ng-repeat 中一次绑定(bind)后的 AngularJS 过滤器

c++ - 具有默认 utf8 处理的流

javascript - jquery 表单验证在 ajax 提交期间不起作用

javascript - 我如何让一个函数找到两个元素?