我正在调用一个函数df(stuff,morestuff),它从html中的firebase返回数据。但是该函数最终没有返回任何数据,因为它是异步函数。该怎么做??
<div>{{ df(stuff, morestuff) }}</div>
$scope.df = function(stuff, morestuff){
ref.child(stuff).child(morestuff).once('value', function(dataSnap){
return dataSnap.val();
})
}
这里非常感谢帮助。
答案 0 :(得分:0)
您无法返回尚未加载的数据。解决方案是将代码改为&#34;当数据加载时,执行...&#34;。
function(stuff, morestuff){
ref.child(stuff).child(morestuff).once('value', $timeout(function(dataSnap){
$scope.df = dataSnap.val();
}));
}
这样做的好处是,当您使用on()
(而不是once()
)时它甚至可以工作,并且在这种情况下会在数据更新时自动更新AngularJS视图。
答案 1 :(得分:0)
很简单,你做一个变量的绑定,并在控制器中用你想要的任何东西填充这个变量。
HTML:
<div>{{variable}}</div>
控制器:
app.controller('appCtrl', ['$scope', function ($scope) {
ref.child(stuff).child(morestuff).once('value', function(dataSnap){
$scope.variable = dataSnap
// Verify if angular isn't digesting already (procesing changes)
if(!$scope.$$phase) {
// Angular ain't aware of changes, so we make it do it's cycle.
$scope.$apply()
}
})
}])