Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角火收集长度_Javascript_Angularjs_Firebase_Angularfire - Fatal编程技术网

Javascript 角火收集长度

Javascript 角火收集长度,javascript,angularjs,firebase,angularfire,Javascript,Angularjs,Firebase,Angularfire,我试图获取简单angularFireCollection的数组长度,但似乎无法: var stf = new FireBase("http://myfirebase-app.firebaseio.com/staff"); function staffListCtrl($scope, angularFireCollection){ $scope.staff = angularFireCollection(stf); console.log($scope.staff.length)

我试图获取简单
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任务。

您试图在调用
angularFireCollection
后立即访问长度,但实际数据是通过网络检索的,因此需要一段时间来更新数组。您可以将函数作为a传递rgument到angularFireCollection,以通知何时加载初始数据,如下所示:

var stf=新FireBase(“http://myfirebase-app.firebaseio.com/staff");
函数staffListCtrl($scope,angularFireCollection){
$scope.staff=angularFireCollection(stf,函数(){
log($scope.staff.length);
});
}   

在这种情况下,打印回调中检索到的元素数的正确方法如下:

var stf = new FireBase("http://myfirebase-app.firebaseio.com/staff");
function staffListCtrl($scope, angularFireCollection) {
    $scope.staff = angularFireCollection(stf, function() {
        console.log(stf.numChildren());
    });
}  

原因是在实际分配给$scope.staff之前调用了初始回调函数。因此,在回调函数中,您只能访问Firebase DataSnapshot对象stf。希望这能有所帮助。

啊,我在angularfire.js中看到了它。第298行包装了在$timeout中添加项目。这导致在将数据添加到集合之前调用initalCb()。我拉了$timeout,它成功了。但是,然后我不得不调用$scope。$apply()来反映添加的项。我最终将scope传递到angularFireCollection以确保调用$apply()。不知道拉超时还会破坏什么

这是对这个问题的看法:

编辑: 据我所知,这是行不通的

$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
    });
});

刚刚发现
ng hide=“staff.length>0”
在我的视图中有效,但在控制器中无效。对于这个愚蠢的问题,我很抱歉,但我一直在苦苦思考为什么我无法在控制器中获取长度。这个问题仍然没有答案,但我会尽快检查它。谢谢,@Anant!它在您的视图中有效,因为加载初始数据后视图会更新。在控制器中,您必须等待第二个函数启动,然后才能查找长度,就像在我的代码片段中一样。我看到了同样的情况。我设置了此plunkr,但您需要添加您的firebase url