简体   繁体   English

在观察angular-chart.js的变化吗?

[英]Watching for changes in angular-chart.js?

I am making a request to a rethinkdb database, grabbing the info and doing a couple manipulations to it so that I have the information I need, and then populating a line chart with data. 我向rethinkdb数据库发出请求,获取信息并对其进行一些操作,以便获得所需的信息,然后使用数据填充折线图。 I am using the angular-chart.js directive, and my issue is that I need to basically re-render the chart after the data manipulations complete. 我正在使用angular-chart.js指令,而我的问题是,在数据操作完成之后,我需要基本上重新呈现图表。 Is there a way that I can do this with a watcher? 有没有办法让观察者做到这一点?

  $scope.things = [];
  $scope.chartData = ChartService.getAll();
  setTimeout(function() {
    var length = $scope.chartData.$$state.value.data.length;
    for (var i = 0; i < length; i++) {
      $scope.things[i] = angular.copy($scope.chartData.$$state.value.data[i].State);
    }
    console.log("Things: " + $scope.things);
    var object = {};
    var array = $scope.things;
    for (var i = 0, j = array.length; i < j; i++) {
      object[array[i]] = (object[array[i]] || 0) + 1;
    }
    console.log("Object: " + JSON.stringify(object));
    $scope.labels = [object];
    console.log("Labels: " + $scope.labels);
  }, 2000);

So I create an empty array, then make a call to my service and push the data I get back into the array. 因此,我创建了一个空数组,然后调用了我的服务,并将获取的数据推回到该数组中。 Then I run a for loop on it to add the number of each array element (in this case I am getting back different state abbreviations) to an object. 然后,在其上运行for循环,以将每个数组元素的数量(在这种情况下,我将获得不同的状态缩写)添加到对象中。 The object looks something like {"AZ": 1, "OH": 5, etc....}. 该对象的外观类似于{“ AZ”:1,“ OH”:5,等等...}。 Basically then I need the graph to re-render at this point with the new data. 基本上,我此时需要使用新数据重新绘制图形。 I assumed a watcher would be the answer but any suggestions are welcome. 我以为观察员会是答案,但任何建议都可以接受。 Thanks! 谢谢!

I would make the ChartService return a promise. 我会让ChartService返回一个承诺。 This will let you do your manipulations/rendering after you get your data. 这将使您在获取数据后进行操作/渲染。

var app = angular.module('plunker', []);

app.controller('ChartController', function($scope, ChartService) {
  ChartService.getAll().success(function(chartData) {
    $scope.chartData = chartData;
    // do you data manipulations here
    // call your chart renderer here
  });
});

app.factory("ChartService", function($http) {
  var service = {};

  service.getAll = function() {
    return $http.get("api/states").success(function(states) {
      // do some stuff
    })
  }

  return service;
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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