Refreshing scope variable not working with scope f

2019-09-09 21:38发布

I'm trying to update data of my chart using chartJS and its wrapper angular-chart. When a button is clicked, it adds data on the chart, no problem with this.

I have another event, which update the chart after a scroll event. The call works great, and it calls exactly the same function as previous. But my $scope.valuesData isn't updated . Then I added a $scope.$apply() after the function, and it redraws the whole chart with the right values.

Question are :

  1. Why does my $scope.chartValues is not updated when I call the function AddData from the controller (and why is $scope.chartValues is updated when I call the function from the DOM). It is probably a data-binding issue ?

  2. Is it a function that update only a specific scope variable, instead of refreshing the whole scope ?

My code :

HTML :

<ion-scroll zooming="false" direction="x" delegate-handle="scroller" on-scroll="getScrollPosition()" has-bouncing="true" scroll-event-interval="30000">
  <div class="chart_wrapper" ng-style="{ 'width': myWidth + '%' }"> 
      <canvas  class="chart-bar" chart-data="data2" chart-labels="labels" chart-dataset-override="datasetOverride2" chart-options="options2" ng-click="goToMetrics()" ">
      </canvas>    
 </div>
</ion-scroll>

<button class="button button-small button-calm" ng-click="addValues()">Add Data </button>

JS (controller) :

  $scope.getScrollPosition = function(){
  var pos =             $ionicScrollDelegate.$getByHandle('scroller').getScrollPosition().left ; 
  if (pos == 0 && $scope.flag == -1){
     $scope.flag = 0;
     //setTimeout($scope.addValues(), 1000);
     $scope.addValues();
  }
  if (pos < 0){
    $scope.flag = -1;
  }
 };


  $scope.addValues = function(){
  console.log('add');
  // Retrieve values
  var week = Graph.getData();
  var pp = $scope.chartData; 
  var mm = $scope.labels;

  // Add values to the chart and update the chart width 
  var tmp = Graph.addBegin(pp, mm,  week);
  $scope.valuesData = tmp.values; 
  $scope.myWidth = $scope.myWidth + tmp.length * 4 ; 
 };

Any help appreciated

1条回答
Juvenile、少年°
2楼-- · 2019-09-09 22:07
  1. Because setTimeout runs outside angular context, use $timeout version.
  2. Nope. You can use $scope.$digest(), to check changes from current scope, not all $scope tree;
查看更多
登录 后发表回答