繁体   English   中英

仅查看一个更新中使用的AngularJS + D3多个指令

[英]AngularJS + D3 Multiple Directives Used In View Only One Updates

我有一个仪表图指令,该指令需要多次放置在视图中,但是控制器中的update方法似乎只能更新视图中的最后一个指令。 最初我以为也许我没有将范围设置为以前遇到过的隔离范围,但事实并非如此,那会抛出一个错误,但是视图确实加载了所有图表,但是只更新一个。

编写了指令的代码库来提供帮助,并且在下面包含了指令和控制器的基本存根。 注意:刚开始使用D3并在指令中实现它,所以存在一个问题,当您调整浏览器的大小时,指令会倍增(试图使其具有响应性),因此您可能在调整了Codepen中的浏览器窗口大小后点击了保存。

  .directive('d3Gauge', [
    'D3GaugeConfig',
    function(D3GaugeConfig) {

      return {
        restrict: 'E',
        scope: {
          title: '@chartTitle',
          config: '=chartConfig',
          data: '=chartData'
        },
        link: link,
        template: '<div>{{d3GaugeCtrl.title}}</div>',
        controller: 'D3GaugeController',
        controllerAs: 'd3GaugeCtrl',
        bindToController: true
      };

      function link($scope, $element, $attrs) {
         ...

        // Browser onresize event
        $window.onresize = function() {
          $scope.$apply();
        };

        // Watch for resize event
        $scope.$watch(function() {
          return angular.element($window)[0].innerWidth;
        }, function() {
          render($element, $scope.data);
        });

        $scope.update = update;
      }

      function render(element, newValue) {
         ...
      }

      function update(newValue, newConfiguration) {

         ...
      }
    }
  ])

  .controller('D3GaugeController', [
    '$scope',
    function($scope) {

      var vm = this;

      function updateReadings() {

        // Just pump in random data here...
        if (angular.isDefined($scope.update)) {
          $scope.update(Math.random() * 100);
        }
      }

      // Every few seconds update reading values
      updateReadings();

      setInterval(function() {
        updateReadings();
      }, 5 * 1000);
    }
  ]);

最后一个度量值发生变化的原因是:

您正在存储存储最后一条路径的变量指针。

pointer = pg.append('path')
  .attr('d', pointerLine)
  .attr('transform', 'rotate(' + config.minAngle + ')');

所以现在当你做

 pointer
      .duration(config.transitionMs)
      .ease('elastic')
      .attr('transform', 'rotate(' + newAngle + ')');

只有最后一个指针将使用新的变换进行更新。

因此,如果要为相同的随机值更新所有量规路径,请执行以下操作:

//select all the path in all svg with group class pointer  
d3.selectAll("svg .pointer path").transition()
          .duration(config.transitionMs)
          .ease('elastic')
          .attr('transform', 'rotate(' + newAngle + ')');//update the new angle

这里的工作代码

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM