简单的AngularJS动态条形图

时间:2016-10-04 07:35:47

标签: angularjs

我正在尝试使用AngularJS创建一个非常简单的动态条形图1.我一直收到一个错误,我认为这是在渲染图表之前使用Angular加载DOM:

Cannot read property 'offsetWidth' of null

原始代码:https://codepen.io/tomesch/pen/itjqk?editors=0010#0

控制器

var values = [85,95,120,100,200,200,230,230,60,320,23,3433,434,45,23,23];

$scope.drawChart = function (data,selector,padding){
    var max = Math.max.apply(Math, data);
    var chart = document.querySelector(selector);
    var barwidth = ((chart.offsetWidth-(values.length-1)*padding-(data.length)*10)/data.length);
    var sum = data.reduce(function(pv, cv) { return pv + cv; }, 0);
    var left = 0;
    for (var i in data){
      var newbar = document.createElement('div');
      newbar.setAttribute("class", "bar");
      newbar.style.width=barwidth+"px";
      newbar.style.height=((data[i]/max)*100)+"%";
      newbar.style.left=left+"px";
      chart.appendChild(newbar);
      left += (barwidth+padding+10);
    }
}

$scope.drawChart(values,"#chartxx",5) // You can adjust the margin between each bar by changing 10 to whatever you like

HTML

  <div class="wrapperx2">
    <div id="chartxx"></div>  
  </div>

0 个答案:

没有答案