在 AngularJS 中显示有关气泡图 D3.js 的信息

Display informations about a bubble chart D3.js in AngularJS

我正在搜索如何在 AngularJS 中显示有关气泡 D3.js 的信息。我可以显示包含所需信息的警报,但我无法使用 AngularJS 在页面上显示信息,因为我无权访问 $scope,因为我的 graphe 在指令中...... 如何在不更改网络应用程序结构的情况下传递信息?我不能将气泡图的结构放在该指令之外。 这是我的 HTML :

  <body ng-app="d3DemoApp">
    <div id="graph1" ng-controller="controllerBubble">
      The package name should appear here : {{packageName}}
      <bubble-chart chart-data="chartData"></bubble-chart>
    </div>
  </body>

服务:

d3DemoApp.service('dataService', function AppCtrl($http, $q) {
  this.getCommitData = function(param) {
    var deferred = $q.defer();
    $http({
      method: 'GET',
      url: param
    }).
    success(function(data) {
      deferred.resolve({
        chartData: data,
        error: ''
      });
    }).
    error(function(data, status) {
      deferred.resolve({
        error: status
      });
    });
    return deferred.promise;
  };
});

控制器:

var d3DemoApp = angular.module('d3DemoApp', []);

// controller business logic
d3DemoApp.controller('controllerBubble', function AppCtrl($rootScope, $scope, dataService) {

  $scope.choice = 'data.json';

  loadData($scope.choice);

  function loadData(param) {
    dataService.getCommitData(param).then(function(res) {
      if (res.error) {
        $scope.error = res.error;
        return false;
      }
      $scope.chartData = res.chartData;
    });
  }

});


d3DemoApp.directive('bubbleChart', function() {
  return {
    restrict: 'EA',
    transclude: true,
    scope: {
      chartData: '='
    },
    link: function(scope, elem, attrs) {

      scope.$watch('chartData', function(newValue, oldValue) {
        console.info('new data comes to directive');
        console.info(newValue);
        if (newValue) {
          scope.drawChart(newValue);
        }
      });

      scope.drawChart = function(rootData) {

        var diameter = 900,
          format = d3.format(",d"),
          color = d3.scale.category20c();

        var bubble = d3.layout.pack()
          .sort(null)
          .size([diameter, diameter])
          .value(function(d) {
            return (d.numberOfLink + 1);
          })
          .padding(1.5);

        var svg = d3.select("body").append("svg")
          .attr("width", diameter)
          .attr("height", diameter)
          .attr("class", "bubble");

        var filt = svg.append("defs")
          .append("filter")
          .attr({
            id: "f1",
            x: 0,
            y: 0,
            width: "200%",
            height: "200%"
          });
        filt.append("feOffset").attr({
          result: "offOut",
          "in": "sourceAlpha",
          dx: 10,
          dy: 10
        });
        filt.append("feGaussianBlur").attr({
          result: "blurOut",
          "in": "offOut",
          stdDeviation: 10
        });
        var feMerge = filt.append("feMerge");
        feMerge.append("feMergeNode").attr("in", "offsetBlur")
        feMerge.append("feMergeNode").attr("in", "SourceGraphic");

        var node = svg.selectAll(".node")
          .data(bubble.nodes(classes(rootData))
            .filter(function(d) {
              return !d.children;
            }))
          .enter().append("g")
          .attr("class", "node")
          .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
          });

        node.append("title")
          .text(function(d) {
            return d.className + ": " + format(d.value);
          });

        node.append("circle")
          .attr("r", function(d) {
            return d.r;
          })
          .style("fill", function(d) {
            return "red";
          });
        node.append("text")
          .attr("dy", ".3em")
          .style("text-anchor", "middle")
          .text(function(d) {
            return d.className.substring(0, d.r / 3);
          })

        node.on("click", click);
        function click(d) {
          alert(d.packageName);
          $scope.packageName = d.packageName; // How to access to the scope ?
          }

        // Returns a flattened hierarchy containing all leaf nodes under the root.
        function classes(root) {
          var classes = [];

          function recurse(name, node) {
            if (node.children) node.children.forEach(function(child) {
              recurse(node.name, child);
            });
            else classes.push({
              packageName: name,
              className: node.name,
              value: node.numberOfLink,
              idProjet: node.projectId,
              numberOfLink: node.numberOfLink,
              priority: node.priority
            });
          }

          recurse(null, root);
          return {
            children: classes
          };
        }
        d3.select(self.frameElement).style("height", diameter + "px");
      }


      if (typeof scope.chartData != "undefined") {
        scope.drawChart(scope.chartData);
      }
    }
  };
});

这是 Plunker 问题的在线示例:https://plnkr.co/edit/LUa7RHxjSaVe1KTzy33c?p=preview

希望有人能制作出Plunker的作品!谢谢。

结果如下:https://plnkr.co/edit/CnoTA0kyW7hWWjI6DspS?p=preview

您必须在您的控制器之间创建共享 service/factory 才能执行此操作。那里有很多例子。

angular.module('d3DemoApp').factory('NotifyingService', function($rootScope) {
    return {
        subscribe: function(scope, callback) {
            var handler = $rootScope.$on('notifying-service-event', callback);
            scope.$on('$destroy', handler);
        },

        notify: function(msg) {
            $rootScope.$emit('notifying-service-event', msg.packageName);
        }
    };
});

我以不同的方式实现,将变量从父范围传递到处于独立范围模式的指令对我来说是一个很好且干净的解决方案,我看到的大多数开源项目都是在同样的方式。 在这种情况下,如果它与您的组件工作流程相关,您甚至可以在指令中调用函数 这是项目的 link 让我知道你的想法 https://github.com/amgadfahmi/angular-bubbletree