2013-09-10 85 views
2

我試圖得到一個簡單的angularFireCollection數組的長度並不能似乎:AngularFire集長度

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輸出。

output of $scope.staff

任何幫助是讚賞,因爲我似乎無法讓過去這個絕對的,簡單得不能再簡單的JS任務。

回答

1

在這種情況下,打印的回調中檢索到的元素的數量的正確的方法是下列:

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。希望這可以幫助。

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); 
    }); 
} 
+0

剛剛發現'ng-hide =「staff.length> 0」'工作在我看來,但不是在控制器。對不起,這個愚蠢的問題,但我掙扎着爲什麼我不能在控制器中獲得長度。這個問題仍然沒有答案,但我會盡快檢查它,只要我能得到它的工作。謝謝,@Anant! – seangates

+0

它在您的視圖中工作,因爲視圖在初始數據加載後更新。在控制器中,在查找長度之前,您必須等待第二個函數啓動,就像在我的代碼片段中一樣。 – Anant

+0

儘管如此,它甚至在回調中都不起作用。 – seangates

0

啊,我在angularfire.js中看到它。第298行包裝在$ timeout中添加一個項目。這導致initalCb()在數據添加到集合之前被調用。我拉了$超時,它的工作。不過,我不得不調用$ scope。$ apply()來反映添加的項目。我最終將範圍傳遞給了angularFireCollection,以確保$ apply()被調用。不知道還有什麼我拉超時了。

這是問題的一個觀點:plunkr

編輯: 據我可以告訴,並在plunkr表明,這是行不通的。

$scope.staff = angularFireCollection(stf, function() { 
    console.log($scope.staff.length); 
}); 

,並同時拉動了$超時從angularfire.js沒有解決這個特定的問題,它造成其他各種頭痛與數據綁定(如預期),所以我把它放回去。似乎要走的路線是使用回調中傳遞的快照。我找不到很多文檔,但這裏是什麼對我有用:

$scope.staff = angularFireCollection(stf, function(snapshot) { 
    angular.forEach(snapshot, function(item){ 
     //will let you iterate through the data in the snapshot 
    }); 
});