避免ng-repeat修改使用同一指令的所有项目

时间:2019-03-08 15:06:14

标签: javascript angularjs angularjs-directive

我有一个名为abx-gauge-chart-resizer的angularjs指令,它对在ng-repeat内重复的某些对象执行更改。这是HTML代码:

<li gridster-item="widget" abx-on-resize="$grid.updateChart(widget.name)" ng-class="{'selected': widget.chart.showPopup}"
  class="grid-item" ng-repeat="widget in $grid.widgets track by $index" id="widget-{{$index}}" abx-gridster-item-initialize
  abx-gridster-event-manager="$grid.updateWidget(widget)" abx-widget-watcher="$grid.updateWidget(widget)">
  <div class="gauge-container" ng-if="widget.chart.provider === 'gauge'" abx-gauge-chart-resizer widget="$grid.modifiedWidget"
    chart="widget.chart">
    <ng-gauge class="abxGauge" ng-if="widget.chart.data.max !== 0" abx-gauge-chart max="widget.chart.data.max" min="widget.chart.data.min"
      size="{{ widget.chart.options.size }}" type="{{ widget.chart.options.type }}" thick="{{ widget.chart.options.thick }}"
      value="widget.chart.data.avg" cap="{{ widget.chart.options.cap }}" label="{{$ctrl.chartReportType === 'rate' ? '' : ('ap.rqa.home.minutes' | translate) }}"
      foreground-color="{{ widget.chart.options.foregroundColor }}" background-color="{{ widget.chart.options.backgroundColor }}">
    </ng-gauge>
  </div>
</li>

这是指令代码:

export default angular.module('fakiyaMainApp.directives.abxGaugeChartResizer', [])
  .directive('abxGaugeChartResizer', ($timeout)=>{
    return {
      restrict: 'A',
      scope: {
        widget: '=',
        chart: '='
      },
      link: function(scope){
        let mainChartSize = 150;
        let mainChartScale = 9;
        let resizeChart = function(){
          console.log(scope.chart);
          let widgetWidth = scope.widget.width;
          let widgetHeight = scope.widget.height;
          if((widgetWidth - widgetHeight) <= Math.floor(mainChartScale/2)){
            let scaleSize = widgetWidth >= mainChartScale ? widgetWidth / mainChartScale : mainChartScale / widgetWidth;
            scope.chart.options.size = Math.round(mainChartSize * scaleSize);
          }
          else{

          }
        };

        scope.$watch('widget', (newValue, oldValue)=>{
          if(newValue && oldValue && (newValue != oldValue)){
            $timeout(()=>{
              resizeChart();
            });
          }
        });
      }
    };
  })

该指令的基本作用是检查范围内的widget的值,并根据chart的大小值调整widget的新值。

问题是当我仅修改一个chart而不是仅修改属于该widget的{​​{1}}时,正在修改{strong> ALL 值。选择chart

如何避免这种情况?

谢谢。

0 个答案:

没有答案