我试图得到一个简单的angularFireCollection
数组的长度,但似乎不能:
var stf = new FireBase("http://myfirebase-app.firebaseio.com/staff");
function staffListCtrl($scope, angularFireCollection){
$scope.staff = angularFireCollection(stf);
console.log($scope.staff.length);
}
控制台中的输出显示:
0
我知道的是不正确的。它应该以大约5的长度返回(参见下面的$scope.staff
输出。
任何帮助都是值得赞赏的,因为我似乎无法通过这个绝对,完全简单的JS任务。
答案 0 :(得分:1)
在这种情况下,在回调中打印检索到的元素数量的正确方法如下:
var stf = new FireBase("http://myfirebase-app.firebaseio.com/staff");
function staffListCtrl($scope, angularFireCollection) {
$scope.staff = angularFireCollection(stf, function() {
console.log(stf.numChildren());
});
}
原因是初始回调函数在
答案 1 :(得分:0)
您正在尝试在调用angularFireCollection
后立即访问该长度,但实际数据是通过网络检索的,因此需要一段时间才能更新阵列。您可以将一个函数作为参数传递给angularFireCollection,以便在加载初始数据时得到通知,如下所示:
var stf = new FireBase("http://myfirebase-app.firebaseio.com/staff");
function staffListCtrl($scope, angularFireCollection) {
$scope.staff = angularFireCollection(stf, function() {
console.log($scope.staff.length);
});
}
答案 2 :(得分:0)
啊,我在angularfire.js中看到了。第298行包装在$ timeout中添加项目。这导致initalCb()在数据添加到集合之前被调用。我拉了$超时,它起作用了。但是,我必须调用$ scope。$ apply()来反映添加的项目。我最终将范围传递给angularFireCollection,以确保调用$ apply()。不知道我拉断超时后还有什么打破了。
这是一个问题的视图:plunkr
编辑: 据我所知,并在plunkr中显示,这不起作用。
$scope.staff = angularFireCollection(stf, function() {
console.log($scope.staff.length);
});
虽然从angularfire.js拉出$ timeout确实修复了这个特定的问题,它引起了数据绑定的各种其他问题(如预期的那样),所以我把它放回去了。似乎要走的路是使用回调中传递的快照。我找不到很多关于它的文档,但是这对我有用:
$scope.staff = angularFireCollection(stf, function(snapshot) {
angular.forEach(snapshot, function(item){
//will let you iterate through the data in the snapshot
});
});