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

我对指令进行了codepen的帮助,并在下面包含了指令和控制器的基本存根。注意:才刚刚开始使用D3并在指令中实现它,因此存在一个问题,当您调整浏览器的大小时,指令会倍增(试图使其具有响应性),因此您可能需要在代码笔中调整浏览器窗口的大小后点击保存。

  .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


工作代码here

希望这可以帮助!

关于javascript - 仅查看一个更新中使用的AngularJS + D3多个指令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34015865/

10-11 23:25
查看更多