Refreshing scope variable not working with scope function

老子叫甜甜 提交于 2019-12-12 05:15:43

问题


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:


  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;


来源:https://stackoverflow.com/questions/39412210/refreshing-scope-variable-not-working-with-scope-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!