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

时间:2016-05-18 08:23:11

标签: angularjs d3.js angular-directive bubble-chart angular-controller

我正在搜索如何在AngularJS中显示有关气泡D3.js的信息。我可以显示包含所需信息的警报,但我无法在AngularJS页面上显示信息,因为我无法访问$ scope,因为我的graphe在指令中...... 如何在不更改Web应用程序结构的情况下传递信息?我不能把这个指令的形成气泡图放在外面。 这是我的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的作品!感谢。

2 个答案:

答案 0 :(得分:1)

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

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

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);
        }
    };
});

答案 1 :(得分:0)

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

相关问题