我正在使用ng-repeat
从Firebase打印数组数据。如下所示; foreeach quote我想计算与之相关的所有投票但是任何迭代的尝试都会导致undefined
我的标记
<div ng-repeat="q in quotes" ng-init="total_votes(q)">
{{q.name}}
</div>
我的控制器
app.controller('account', function ($scope, $timeout, $rootScope, $location, $firebaseObject, $firebaseArray) {
//======== Get Quotes ========//
var ref = firebase.database().ref().child('quotes');
$scope.quotes_obj = $firebaseObject(ref);
$rootScope.quotes = $firebaseArray(ref);
//======== item totals ========//
$scope.total_votes = function(itm) {
// attempt ONE
var itm_votes = $scope.quotes_obj[itm.$id].votes;
console.log(itm_votes); // returns "{-KzFkQYHWKwbAPjIekWz: "sad", -KzLT76T14doKgYbjRc1: "wow"}"
console.log(itm_votes.length); // returns "undefined"
// attempt TWO
console.log(itm.votes) // returns "{-KzFkQYHWKwbAPjIekWz: "sad", -KzLT76T14doKgYbjRc1: "wow"}"
console.log(itm.votes[0]) // returns "undefined"
console.log(itm.votes.length) // returns "undefined"
// count votes
var counts = {};
for (var i = 0; i < itm_votes.length; i++) {
counts[itm_votes[i]] = 1 + (counts[itm_votes[i]] || 0);
if(i == itm_votes.length){
console.log('done');
}
}
return counts;
};
});
有谁知道为什么数据的索引未定义?如果你看到这种方法有问题,我愿意接受新方法来计算所有类似的选票
什么都有帮助。谢谢!答案 0 :(得分:1)
我必须$.map
将obj转换为数组。
$scope.total_votes = function(itm) {
var itm_votes = $.map($scope.quotes_obj[itm.$id].votes, function(value, index) {
return [value];
});
console.log(itm_votes.length);
var counts = {};
for (var i = 0; i < itm_votes.length; i++) {
counts[itm_votes[i]] = 1 + (counts[itm_votes[i]] || 0);
if(i == itm_votes.length-1){
console.log('done');
console.log(counts);
}
}
return counts;
};