我在 AngularJS 应用程序中使用 Dygraphs 来显示来自数据记录器的数据的时间序列图。当数据到达时,Angular 会处理检索新数据并更新图形系列,而 Dygraphs 正在使用 Angular 很好地更新绘图$watch()
。当我想切换到一组不同的数据,特别是包含较少系列的数据时,就会出现问题。我看到一个控制台错误(在 OS X 10.6.8 上使用 Safari 5.1.9):
'undefined' is not an object (evaluating 'this.series_[b].yAxis')
在第 2 行dygraph-combined.js
。似乎没有发生任何不愉快的事情,并且图表更新正确,但我宁愿它没有发生!
我在让 Angular 正确切换图形数据源时遇到了一些问题:对我有用的是在$timeout(,0)
调用中更改数据源,同时立即更改其他选项。这意味着系列数量与系列标题和/或轴的数量之间将存在(短暂的)不匹配。如果系列数没有变化或增加,我不会收到此错误。谁能看到出了什么问题,并告诉我如何避免它?
我编写了一个 Angular 指令来实例化一个 Dygraph:
'use strict';
angular.module('dygraphs', []);
angular.module('dygraphs').directive('mrhDygraph', function ($parse, $q) {
return {
restrict: 'A',
replace: true,
scope: {data: '=', initialOptions: '@', options: '='},
link: function (scope, element, attrs) {
var dataArrived = $q.defer();
dataArrived.promise.then(function (graphData) {
scope.graph = new Dygraph(element[0], graphData, $parse(scope.initialOptions)(scope.$parent));
return graphData.length - 1;
}).then(function(lastPoint) {
scope.graph.setSelection(lastPoint);
scope.$emit('dygraphCreated', element[0].id, scope.graph);
});
var removeInitialDataWatch = scope.$watch('data', function (newValue, oldValue, scope) {
if ((newValue !== oldValue) && (newValue.length > 0)) {
dataArrived.resolve(newValue);
removeInitialDataWatch();
scope.$watch('data', function (newValue, oldValue, scope) {
if ((newValue !== oldValue) && (newValue.length > 0)) {
var selection = scope.graph.getSelection();
scope.graph.updateOptions({'file': newValue});
if ((selection >= 0) && (selection < newValue.length)) {
scope.graph.setSelection(selection);
}
}
}, true);
scope.$watch('options', function (newValue, oldValue, scope) {
if (newValue !== undefined) {
scope.graph.updateOptions(newValue);
}
}, true);
}
}, true);
}
};
});
然后在我的控制器中,我像这样切换图形数据源:
$scope.setGraphDataSource = function (plotData, sourceData, scaleFactor) {
$timeout(function () {
$scope[plotData] = [];
for (series in removeWatch) {
removeWatch[series]();
}
removeWatch = [];
var col = 0;
for (series in sourceData) {
removeWatch[series] = function (col) {
return $scope.$watch(function () {return $scope.logs[sourceData[col]].data.length},
function (newValue, oldValue, scope) {
updateCol(plotData, col, scope, scope.logs[sourceData[col]],
sourceData.length + 1, scaleFactor[col]);
})}(col);
col = col + 1;
}
}, 0);
}
$scope.showTemperatureGraph = function () {
$scope.setGraphDataSource('graphData', ['OutsideTemperature', 'InsideTemperature'], [1, 1]);
$scope.graphOptions = {labels: ['Time', 'Outside', 'Inside'],
series: {'Inside': {axis: 'y'}, 'Outside': {axis: 'y'}},
axes: {x: {valueFormatter: function (ms) {return $filter('date')(new Date(ms), 'dd/MM HH:mm')}},
y: {valueFormatter: function (num) {return num.toFixed(1)}}
},
xlabel: 'Local Time', ylabel: 'Temperature (ºC)', stepPlot: false};
};
欢迎任何建议,评论甚至答案!
谢谢