在Angular中构建一个可重复使用的D3.js图表,其宽度为100%

Building a reusable D3.js chart in Angular with 100% width?

本文关键字:js 图表 D3 100% 构建 Angular 一个      更新时间:2023-11-04

我正在Angular中基于这个例子构建一个D3.js条形图指令。

到目前为止,它运行得很好,但现在我遇到了障碍。我希望我的图表是一个流动的宽度,而不是固定的,并设置为包含元素宽度的100%。

我知道如何在指令中重新绘制调整大小时的图形:

    link: function(scope, iElement, iAttrs) { 
      var chartEl = d3.select(iElement[0]);
      window.onresize = function() {
          return scope.$apply();
      };
      scope.$watch(function(){
            return angular.element(window)[0].innerWidth;
        }, function(){
            chartEl.datum(scope.data).call(chart);
        }
      );
    }

这会重新绘制图形,但我如何将指令中的窗口宽度传递到条形图模块中,而不是使用目前500像素的固定宽度?我需要将宽度附加到data吗?或者有其他方法吗?

更新:JSFiddle在这里:http://jsfiddle.net/XCLR7/

尚未测试,但应该可以使用:

window.onresize = function() {
    chartEl.call(chart.width($(iElement[0]).width()));      
};

调整大小时:获取宽度,更新图表的宽度,然后重新绘制图表。除非您需要显示图表的当前宽度或在图表之外使用它,否则没有任何理由将宽度存储在范围内或使用手表。

我使用this.offsetWidth,其中"this"是div元素。经过几次迭代,以下是我最终得到的结果。即使使用exports.width().更新宽度,也能正常工作

d3.custom.barChart = function module() {
  var width = 1000, // Update width in selection.each
      height = 500,
      widthFromElement = true,
      heightFromElement = true
  ...
  function exports(_selection) {
    _selection.each(function(_data) {
      width = widthFromElement ? this.offsetWidth || width : width
      height = heightFromElement ? this.offsetHeight || height : height
      ...
    })
  }
  ...
  exports.width = function(_x) {
    if (!arguments.length) return width;
    widthFromElement = false
    width = parseInt(_x);
    return this;
  };