【问题标题】:Display informations about a bubble chart D3.js in AngularJS在 AngularJS 中显示有关气泡图 D3.js 的信息
【发布时间】:2016-09-14 14:39:51
【问题描述】:

我正在搜索如何在 AngularJS 中显示有关气泡 D3.js 的信息。我可以显示带有所需信息的警报,但我无法使用 AngularJS 在页面上显示信息,因为我无法访问 $scope,因为我的图形位于指令中... 如何在不更改 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 的作品!谢谢。

【问题讨论】:

  • 我不太明白这个问题。您需要提示而不是警报吗?只需将警报替换为提示 (plnkr.co/edit/Yj6XgLeSdvw7YwVKURbL?p=preview)。你想用提示做什么?
  • 您好,我希望信息出现在我的网页上,例如段落或 div...
  • 不,在我的网页上使用此代码:The package name should appear here : {{packageName}}

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


【解决方案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);
        }
    };
});

【讨论】:

  • 我已经读过了,但我不明白我应该怎么做。
  • 嗨,谢谢它有效,我想添加其他信息,但它会删除第一个信息:plnkr.co/edit/f0D34h4LqXdlkENLZrDd?p=preview 你能检查一下吗?谢谢。
  • @afeffifari-1957 我不知道你有什么改变,但这是一个有效的..plnkr.co/edit/CnoTA0kyW7hWWjI6DspS?p=preview
  • @afeffifari-1957 您已将 function somethingChanged(e,msg, msgPriority) 设置为 3 个输入,但此处仅提供 2 个输入 $rootScope.$emit('notifying-service-event', msg.packageName);
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 2016-03-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多