中显示有关气泡图

中显示有关气泡图

本文介绍了在 AngularJS 中显示有关气泡图 D3.js 的信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 

服务:

d3DemoApp.service('dataService', function AppCtrl($http, $q) {this.getCommitData = 函数(参数){var deferred = $q.defer();$http({方法:'获取',网址:参数}).成功(功能(数据){deferred.resolve({图表数据:数据,错误: ''});}).错误(功能(数据,状态){deferred.resolve({错误:状态});});返回 deferred.promise;};});

控制器:

var d3DemoApp = angular.module('d3DemoApp', []);//控制器业务逻辑d3DemoApp.controller('controllerBubble', function AppCtrl($rootScope, $scope, dataService) {$scope.choice = 'data.json';加载数据($scope.choice);函数加载数据(参数){dataService.getCommitData(param).then(function(res) {如果(res.error){$scope.error = res.error;返回假;}$scope.chartData = res.chartData;});}});d3DemoApp.directive('bubbleChart', function() {返回 {限制:'EA',转置:真实,范围: {图表数据:'='},链接:功能(范围,元素,属性){scope.$watch('chartData', function(newValue, oldValue) {console.info('新数据进入指令');控制台信息(新值);如果(新值){scope.drawChart(newValue);}});scope.drawChart = 函数(根数据){var 直径 = 900,格式 = d3.format(",d"),颜色 = d3.scale.category20c();var 气泡 = d3.layout.pack().排序(空).size([直径,直径]).value(函数(d){返回 (d.numberOfLink + 1);}).padding(1.5);var svg = d3.select("body").append("svg").attr("宽度", 直径).attr(高度",直径).attr("class", "bubble");var filt = svg.append("defs").append("过滤器").attr({id: "f1",x: 0,y: 0,宽度:200%",高度:200%"});filt.append("feOffset").attr({结果:关闭","in": "sourceAlpha",dx: 10,日:10});filt.append("feGaussianBlur").attr({结果:模糊","in": "offOut",标准偏差: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)).过滤器(功能(d){返回 !d.children;})).enter().append("g").attr(类",节点").attr(转换",函数(d){返回 "translate(" + d.x + "," + d.y + ")";});node.append("title").text(function(d) {返回 d.className + ":" + format(d.value);});node.append("圆圈").attr(r",函数(d){返回 d.r;}).style(填充",函数(d){返回红色";});node.append("文本").attr("dy", ".3em").style("文本锚", "中间").text(function(d) {返回 d.className.substring(0, d.r/3);})node.on("点击", 点击);功能点击(d){警报(d.packageName);$scope.packageName = d.packageName;//如何访问范围?}//返回包含根下所有叶节点的扁平层次结构.函数类(根){var 类 = [];函数递归(名称,节点){if (node.children) node.children.forEach(function(child) {递归(节点名称,孩子);});其他类.push({包名:名称,类名:节点名,值:node.numberOfLink,idProjet: node.projectId,numberOfLink: node.numberOfLink,优先级:node.priority});}递归(空,根);返回 {孩子:上课};}d3.select(self.frameElement).style("height", 直径 + "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

为了做到这一点,您必须在控制器之间创建一个共享服务/工厂.那里有很多例子.

angular.module('d3DemoApp').factory('NotifyingService', function($rootScope) {返回 {订阅:函数(范围,回调){var handler = $rootScope.$on('notifying-service-event', callback);scope.$on('$destroy', handler);},通知:功能(味精){$rootScope.$emit('notifying-service-event', msg.packageName);}};});

I am searching how to display information about a bubble D3.js in AngularJS. I can show an alert with the desired information but I can't display informations on the page with AngularJS because I have no access to the $scope because my graphe is in a directive...How can I pass the informations without change the structure of the web app ? I can't put the formation the bubble chart outsite of this directive.This is my 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>

The service :

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

The controller :

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

This is an online example of the problem with Plunker : https://plnkr.co/edit/LUa7RHxjSaVe1KTzy33c?p=preview

Hope someone will can make works the Plunker ! Thanks.

解决方案

Here's the result: https://plnkr.co/edit/CnoTA0kyW7hWWjI6DspS?p=preview

You have to create a shared service/factory between your controllers in order to do that. There are lots of examples out there.

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

这篇关于在 AngularJS 中显示有关气泡图 D3.js 的信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:21