簡體   English   中英

將d3與自定義的角度指令集成

[英]Integrating d3 with a custom angular directive

我正在開發一個應用程序,該應用程序使用angular保持來自幾個不同服務的數據同步,並將此數據傳遞給某些d3函數以生成圖形和表格。

現在,我很難在d3代碼中以正確的級別綁定數據。 此時我正在創建一個基本表。

這是我的指令:

application.directive('d3table', function() {
   var chart = table();
   return  {
       restrict: 'E',
       scope: {
        data: "="
       },
       link: function(scope, element, attrs) {
           scope.$watchCollection('data', function(data) {
               d3.select(element[0]).datum(data).call(chart);
           });
       }
   }
});

我的table()的d3代碼如下,使用了朝可重用圖表的方法:

function tableChart() {
    function chart(selection) {
        selection.each(function(dataset) {
            var table = d3.select(this).append('table');

            table.append('thead').append('tr')
              .selectAll('tr').data(columns).enter()
              .append('th').text(function(d) { return d;});
    }
    return chart;
}

我在這里工作的數據是一個簡單的數組。 定期添加和刪除數據。

我遇到的問題是,添加數據而不是更新現有表,而是觸發了新表的生成。 因此,我最終得到多個表,而不是正確綁定到d3函數的表。

您可以事先刪除表格。

function tableChart() {
    function chart(selection) {
        selection.each(function(dataset) {
            //remove existing table
            d3.select(this).select("table").remove();

            var table = d3.select(this).append('table');

            table.append('thead').append('tr')
              .selectAll('tr').data(columns).enter()
              .append('th').text(function(d) { return d;});
    }
    return chart;
}

我將使用一個模板,基本上只在其中包含您的表和表頭信息,然后在鏈接函數中可以獲取對該表的引用。 然后在watch collection函數中,您僅添加或刪除行,而不是每次都嘗試重新創建整個表。 只要您的數據方案保持不變,這種方法就可以工作。

這是一些代碼要看

//js
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'D3 Angular Table';

  $scope.data = [1,2,3,4,5,6,7,8];


  $scope.add = function(){
    console.log('add');
    $scope.data.push(Math.floor(Math.random() * 100) );
  };

   $scope.remove = function(){
    console.log("remove")
     $scope.data.splice(0, 1)
  };
});




app.directive('d3table', function() {
   //var chart = table();
   return  {
       restrict: 'E',
       scope: {
        data: "="
       },
      templateUrl: 'd3table.html',
       link: function(scope, element, attrs) {

           var table = element[0].firstChild;

           scope.$watchCollection('data', function(data) {

             var selectedTable = d3.select(table).selectAll('tr').data(data);

              selectedTable.enter()
              .append("tr")
              .text(function(d){return d});

              selectedTable.exit().remove();

           });
       }
   }
});
//html
<table id = "test" >
  <thead>
     <tr><th>Value</th></tr>
  </thead>
</table>

工作勤奮

http://plnkr.co/edit/hb6t9gshXBngApUGyJkN?p=預覽

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM