【问题标题】:How to use D3 inside a ui-view state如何在 ui-view 状态中使用 D3
【发布时间】:2014-08-05 05:29:20
【问题描述】:

所以我有一个使用 ui-router 的 Angular 应用程序。假设我想在div.wtf中显示一个条形图,就像这样:

index.html

<div ui-view ></div>

state1.html

<div class="wtf"></div>

js:

var dataset = [5,3,2,2,10];
d3.select('.wtf').selectAll('div')
.data(dataset)
.enter()
.append('div')
.attr('class', 'bar')
.style('height', function (d) {
  return d * 5 + 'px';
});

js 必须在控制器中吗?如果是,我如何确保文件准备就绪?

【问题讨论】:

    标签: javascript angularjs d3.js


    【解决方案1】:

    您可以使用自定义指令。它可以访问 DOM 而不会破坏您的控制器。

    app.directive('bindDeeThreeStuff', function($window){
      var d3 = $window.d3;
    
      return function(scope, elem, attrs) {
        var d3Elem = d3.select(elem[0]);
    
        scope.$watch(attrs.bindDeeThreeStuff, function(val) {
          d3Elem.selectAll('.bar').data(val)
            .enter()
            .append('div')
            .attr('class', 'bar')
            .style('height', function(d) {
              return d * 5
            });
        });
      };
    });
    

    在你看来:

    <div bind-dee-three-stuff="myData"></div>
    

    在你的控制器中:

    $scope.myData = [10,20,30,40,50];
    

    编辑:示例

    Here's a quick example of a simple directive that binds data with d3.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      相关资源
      最近更新 更多