我已經成功將我的Firebase綁定到Google Charts上,效果很好,但我在如何顯示一條簡單的消息,指出「無數據」沒有數據可以評估爲我聲明的簡單的if else表達式。當Firebase數據發生變化時,Google Charts不會得到更新
例如,我爲單個用戶設置了「不適用」的Firebase數據值,理論上這意味着圖表不會默認顯示,並且錯誤消息會在頁面加載和任意點顯示這會變回這個值。但是,情況並非如此,觸發它的唯一方法是單擊我在HTML文件中設置的3D按鈕。此外,當Firebase數據更改爲大於零的值時,仍會顯示錯誤消息。
這裏是我的代碼:
JS文件
var displayMode = true;
$scope.statistics = function() {
$mdSidenav('left').close();
$state.go('statistics');
$timeout(function() {
setUpChart();
var timer;
$(window).on('resize', function() {
clearTimeout(timer);
timer = setTimeout(function() {
setUpChart();
}, 250);
});
});
};
function setUpChart() {
$.ajax({
url: '//www.google.com/jsapi',
dataType: 'script',
cache: true,
success: function() {
google.load('visualization', '1', {
'packages': ['corechart'],
'callback': drawChart
});
}
});
function drawChart() {
// This links to my Firebase url
userRef.on('value', function (snapshot) {
var pass = 0;
var fail = 0;
snapshot.forEach(function (snapshot) {
var userResults = snapshot.val();
if (userResults.passFail === 'Pass') {
pass = pass + 1;
}
if (userResults.passFail === 'Fail') {
fail = fail + 1;
}
});
if (pass === 0 && fail === 0) {
console.log('No data: ' + pass + ' & ' + fail);
$scope.error = true;
$scope.errorMessage = 'No user data available, please try
again later.';
} else {
console.log('Is data: ' + pass + ' & ' + fail);
$scope.error = false;
$scope.errorMessage = null;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Result');
data.addColumn('number', 'Delegates');
data.addRows([
['Pass', pass],
['Fail', fail]
]);
var options = {
'is3D': displayMode,
'chartArea': {'width': '100%', 'height': '80%'},
'legend': {'position': 'top', 'alignment': 'center'}
};
var chart = new
google.visualization.PieChart(document.getElementById('pieChart'));
chart.draw(data, options);
}
});
}
}
// Changes chart type to 3D or top view on a butto click
$scope.chartFormat = function() {
if (displayMode == true)
displayMode = false;
else
displayMode = true;
setUpChart();
};
HTML
<div class="container" style="padding-top: 100px; padding-bottom: 50px">
<button data-ng-model="displayType" style="display: block; margin: 0 auto"
data-ng-click="displayType=displayType ? false : true;
chartFormat()"
class="btn btn-default btn-md" type="button"><i class="material-
icons">3d_rotation</i></button>
<div data-ng-if="error" class="alert alert-danger">
<span data-ng-if="errorMessage" class="glyphicon glyphicon-remove">
</span><strong> {{errorMessage}}</strong>
</div>
<div id="pieChart" style="display: block; margin: 0
auto; width: 100%; height: 500px"></div>
</div>
請注意,更新作用域的角度核心外部的代碼需要通知角度來運行摘要。 – charlietfl
可以請你解釋一下,因爲我之前沒有使用過這個方法嗎? –
使用'$ scope。$ apply()' – charlietfl