我在我的單頁應用程序中使用angular-chart.js
http://jtblin.github.io/angular-chart.js/在我的某個視圖中有一個圖表。問題是,當視圖初始化時,圖表不會加載,因爲數據尚未通過API在工廠加載。無論我堅持這種觀點多久,數據都不會填充。但是,如果我對單頁應用程序有不同的看法,並且返回,那麼數據就在那裏,因爲它已經在工廠加載了。在頁面加載時不加載範圍變量AngularJS
這是我的理解,一旦數據從工廠加載,圖表應該立即更新,因爲數據bindingl,但爲什麼它不會在第一個視圖上這樣做?
廠(其中數據經由service.getChartData()
加載)
app.factory('chartFactory', ['$http', function($http) {
var service = {
height_chart: window.innerHeight * 0.4,
labels: [],
series: ['GDAX Value'],
data: [],
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
id: 'y-axis-1',
// type: 'linear',
display: true,
position: 'left',
ticks: {
beginAtZero: false,
callback: function(value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}],
xAxes: [{
display: false
}]
}
},
getChartData: function() {
$http.get('/portfolio/get-chart-data')
.then(function(response) {
service.labels = response.data[0]
service.data = response.data[1]
})
}
}
return service
}])
控制器
app.controller('chartCtrl', chartCtrl)
chartCtrl.$inject = ['$scope', '$interval', 'chartFactory']
function chartCtrl($scope, $interval, chartFactory) {
var vmChart = this
vmChart.height_chart = chartFactory.height_chart
vmChart.labels = chartFactory.labels
vmChart.series = chartFactory.series
//this data hasn't loaded yet.
vmChart.data = [chartFactory.data]
vmChart.onClick = function(points, evt) {
console.log(points, evt)
}
vmChart.datasetOverride = [{
yAxisID: 'y-axis-1'
}]
vmChart.options = chartFactory.options
chartFactory.getChartData()
//the chart never shows up on the first view, even after the function loads the data in the factory.
}
<div ng-controller="chartCtrl as vmChart" class="chart-container">
<canvas id="line" class="chart chart-line" chart-data="vmChart.data" chart-labels="vmChart.labels" chart-series="vmChart.series" chart-options="vmChart.options" chart-dataset-override="vmChart.datasetOverride" chart-click="vmChart.onClick" style="width:100%;">
</canvas>
</div>
只是澄清 - 圖表加載,但直到我切換到不同的視圖,然後再回來。如何獲取圖表加載。數據在工廠加載後的第一個視圖?
儘量把'vmChart.data'承諾'chartFactory.getChartData()。然後(函數(數據){內vmChart.data = data;}' –