简体   繁体   中英

ngRepeat not updating after ajax call

This is part of my view:

<div class="chartspanel">
    <div ng-repeat="(key, chartData) in main.chartsData" class="chart-box">
        <div class="ibox">
            <div class="ibox-title">
                <h3>{{key}}</h3>
            </div>
            <div class="ibox-content" chart="chartData" chart-name="key"></div>
        </div>
    </div>
</div>

now, my controller:

class DashboardCtrl {
  constructor ($scope, $timeout, $sce, $rootScope, ChartService) {
    "ngInject";

    this.$sce = $sce;
    this.$scope = $scope;
    this.$rootScope = $rootScope;
    this.$timeout = $timeout;
    this.chartsData = null;
    this.chartService = ChartService;

    this.loadChartsEvent(this.$scope, this.$timeout, this.chartsData);
  }

  loadChartsEvent (scope, timeout, chartsData) {
      this.$rootScope.$on('loadCharts', (event, data) => {
          timeout(() => {
              scope.$apply(() => {
                  chartsData = data;
                  console.log(chartsData);
              });
          });
      });
  }
}

Data is retrieved from directive using $brodcast, this part is working fine, but after i'm trying to update chartsData in my view ng-repeat is not acting at all, i still have the same commented <!-- ngRepeat: (key, chartData) in main.chartsData --> . Why is that, console log shows proper data from ajax call... Can anybody help?

When you have chartsData = data , all you are doing is changing the object that the local variable chartsData points to. This does not change the actual property that the view is bound to, which is the chartsData property on the controller instance, accessed via this.chartsData .

You do need to set this.chartsData = data for it to work, and your code can be dramatically simplified to remove the redundant $timeout and $scope.$apply() calls.

Try updating your loadChartsEvent to use the this keyword when assigning to the chartsData property, and add a timeout value of 0 in your timeout function to move your call to the end of the stack, your code will become like this:

loadChartsEvent(scope, timeout, chartsData) {
  this.$rootScope.$on('loadCharts', (event, data) => {
      timeout(() => {
          scope.$apply(() => {
              this.chartsData = data;
              console.log(chartsData);
          });
      }, 0);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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