I have an Firebase structure like this:
Chatrooms {
-efsCsTB95 {
Messages {
-bdre3G5 {
Title: ...
}
-wer23bd {
Title: ...
}
}
}
}
I have a view like this:
<div class="card" ng-repeat="list in chatrooms">
<div class="item item-positive item-text-wrap">
{{list.videoTitle}}
</div>
<div class="item item-stable">
<div class="card-footer text-right">
<i class="icon ion-chatbox-working positive"></i>
<b class="positive">{{list.messageCount}}</b>
</div>
</div>
</div>
The list.messageCount try to get the length of the messages node inside the firebaseAarry chatrooms. The message length will be updated when there are more messages inside the room page. Since I cannot get the length of a nested array inside a firebaseArray like list.messages.length, I loop the chatrooms array in side my controller like this:
$scope.chatrooms = $firebaseArray($scope.chatroomsRef);
$scope.chatrooms.$loaded()
.then(function(){
angular.forEach($scope.chatrooms, function(room, key) {
var messagesRef = $rootScope.baseUrl + "chatrooms/" + room.$id + "/messages/";
console.log (messagesRef);
var messagesNode = $firebaseArray(new Firebase(messagesRef));
messagesNode.$loaded().then(function(){
console.log (messagesNode.length);
$scope.chatrooms[key].messageCount = messagesNode.length;
});
$scope.chatrooms.$watch(function() {
messagesNode.$loaded().then(function(){
console.log (messagesNode.length);
$scope.chatrooms[key].messageCount = messagesNode.length;
});
});
});
});
In each loop, I open up another $firebaseArray connection called messagesNode. And I wait till the messagesNode loaded with $loaded, and give it to a new local attribute called messageCount, attached to each room. When there are more messages added to the room, I use $watch to re-get the length and re-attach it to messageCount.
So this solution work. The list.messageCount has live update (2-way binding). BUT, is this the correct solution?! It just seem too much work to just get the length of a array object inside a firebaseArray. If I just use
$scope.chatroomsRef.on('child_added', function(snapshot){
var snapshotVal = snapshot.val();
var messageCount = snapshot.child('messages').numChildren(); });
The messageCount is always updated. It just seem strange the $firebaseArray actually make thing way difficult to do instead of providing helper function like "numChildren()"?! Firebase Expert, please advice the best way to do this kind of simple task.
transactioncalls to update it. At least that way the "counters are a tricky concept to keep in sync" problem will only hurt on writes and not for every read operation. - Frank van Puffelen