2015-06-21 61 views
0

我試圖動態添加一個自定義元素,每當用戶點擊按鈕,這將通過D3.js代碼呈現SVG立方體。如何在角度動態附加自定義D3/SVG元素

我添加了一個ng-click指令給一個按鈕元素,該按鈕元素調用一個函數來動態追加一個自定義多維數據集元素,然後調用$ rootScope。$ apply()以便'應用'自定義指令,但那不起作用。

下面是完整的代碼:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>AngularJS, directives, and D3.js</title> 

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.js"> 
    </script> 

    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> 
</head> 

<body ng-app="myapp" ng-controller="MyController as svgc"> 
    <button ng-click="svgc.addCube()">Add a Cube</button><br/> 
    <cube></cube> 

    <script> 
    var myapp = angular.module('myapp', []); 
    myapp.controller("MyController", function($rootScope) { 
     var svgc = this; 

     svgc.addCube = function() { 
     //var cube = angular.element('cube'); 
      var cube = document.createElement('cube'); 
      document.body.appendChild(cube); 
      $rootScope.$apply(); 
     } 
    }); 

    myapp.directive('cube', function() { 
     function link(scope, el, attr) { 
     // d3.select(el[0]).append('svg'); 
     el = el[0]; 

     // CUSTOM CODE FOR RENDERING A CUBE 
     var width = 300, height = 300; 
     var points1 = "50,50 200,50 240,30 90,30"; 
     var points2 = "200,50 200,200 240,180 240,30"; 
     var fillColors = ["red", "yellow", "blue"]; 

     var svg = d3.select(el) 
        .append("svg") 
        .attr("width", width) 
        .attr("height", height); 

     // top face (parallelogram) 
     var polygon = svg.append("polygon") 
         .attr("points", points1) 
         .attr("fill", fillColors[1]) 
         .attr("stroke", "blue") 
         .attr("stroke-width", 1); 

     // front face (rectangle) 
     svg.append("rect") 
      .attr("x", 50) 
      .attr("y", 50) 
      .attr("width", 150) 
      .attr("height", 150) 
      .attr("fill", fillColors[0]); 

     // right face (parallelogram) 
     var polygon = svg.append("polygon") 
          .attr("points", points2) 
          .attr("fill", fillColors[2]) 
          .attr("stroke", "blue") 
          .attr("stroke-width", 1); 
     } 

     return { 
     link: link, 
     restrict: 'E' 
     } 
    }); 
    </script> 
</body> 
</html> 

我已經看到了使用模板添加自定義元素上計算器的例子,但這種情況下,需要動態生成通過D3 SVG元素,所以我沒有看到如何使用基於模板的解決方案。

我敢肯定,解決方法很簡單......建議,歡迎:)

回答

0

我擺弄的代碼,並用此溶液想出了:

<script> 
    var myapp = angular.module('myapp', []); 
    myapp.controller("MyController", function($compile, $scope) { 
     var svgc = this; 

     svgc.addCube = function() { 
      var cube = document.createElement('cube'); 
      cube.className = "cube"; 
      document.body.appendChild(cube); 
      $compile(angular.element('.cube'))($scope); 
     } 
    }); 
... 
</script>