【问题标题】:D3 and AngularJS directivesD3 和​​ AngularJS 指令
【发布时间】:2014-03-28 19:37:42
【问题描述】:

我正在尝试结合 AngularJS 和 D3 —— 两个很棒的库。这个例子是人为的,但我有一个合法的用例,我想通过 D3 插入带有 AngularJS 指令的 HTML。

这是一个例子:

  • 一个简单的 AngularJS 指令,
  • 使用 D3 简单地添加内容
  • 最后使用 D3 使用 AngularJS 指令添加内容。

最后一个不起作用;为什么?

Here's the Fiddle.

HTML:

<body ng-app="d3">
    <div hello></div>
    <div hello-d3></div>
    <div hello-d3-angular></div>
</body>

JS:

angular.module('d3', [])
  .directive('hello', function() {
      return {
          template: 'Hello Angular!'
      };
  })
  .directive('helloD3', function() {
      return {
          link: function(scope,elt) {
              d3.select(elt[0]).append('div').text('Hello d3!')
          }
      };
  })
  .directive('helloD3Angular', function($compile) {
      return {
          link: function(scope,elt) {
              var node = $compile('<div hello></div>')(scope);
              d3.select(elt[0]).append(node[0]);
          }
      };
  });

【问题讨论】:

    标签: javascript angularjs d3.js


    【解决方案1】:

    我认为是关于 D3 API,selection.append(name)

    名称可以指定为常量字符串或返回要追加的 DOM 元素的函数。

    http://jsfiddle.net/bateast/4SGsc/7/

    因此,如果您想将 DOM 传递给 .append(),请尝试以下操作:

    d3.select(elt[0]).append(function() { return node[0]; });
    

    【讨论】:

    • 呃,我知道我缺少一些简单的东西......谢谢!
    【解决方案2】:

    您可以使用回调箭头函数解决此问题

    d3.select(elt[0]).append(function() {()=> $compile('<div hello></div>')(scope)[0] });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 1970-01-01
      相关资源
      最近更新 更多