Lan*_*ngo 5 angularjs firebase
我想知道如何循环通过孩子们everyone.我正在使用Firebase和AngularJS.
我的firebase对象如下所示:

对我来说,它看起来像一个字典,所以从获取我尝试过的关联数组键列表
syncData('everyone').$bind($scope, 'everyone').then(function() {
var keys = $scope.everyone.$getIndex();
for (var key in $scope.everyone) {
console.log("key : " + key + " value : " + $scope.everyone[key]);
}
});
Run Code Online (Sandbox Code Playgroud)
日志确实包含子对象,但它也包含所有方法.像这样
... Before this line is all the other methods.
key : $on value : function (a,c){if("loaded"==a&&b._loaded)return b._timeout(function(){c()}),void 0;if(!b._on.hasOwnProperty(a))throw new Error("Invalid event type "+a+" specified");b._on[a].push(c)} controllers.js:58
key : $off value : function (a,c){if(b._on.hasOwnProperty(a))if(c){var d=b._on[a].indexOf(c);-1!==d&&b._on[a].splice(d,1)}else b._on[a]=[];else b._fRef.off()} controllers.js:58
key : $auth value : function (a){var c=b._q.defer();return b._fRef.auth(a,function(a,b){null!==a?c.reject(a):c.resolve(b)},function(a){c.reject(a)}),c.promise} controllers.js:58
key : $getIndex value : function (){return angular.copy(b._index)} controllers.js:58
key : -JH45WOOAtnZfUZkrJb1 value : [object Object] controllers.js:58
key : -JH45YdfwptGv3y6UqyV value : [object Object] controllers.js:58
key : -JH45_zxptV_dmibyGzL value : [object Object]
Run Code Online (Sandbox Code Playgroud)
有没有办法让孩子们得到它?
我之所以这样做是因为我的代码设计用于使用数组,但Firebase不鼓励使用数组(对于多人可能更改的值).所以我试图遍历firebase字典并将对象复制到客户端的数组中.所以我不必改变太多的代码.
更新:从 AngularFire 0.8.x 开始,可以使用 $asArray() 来获取记录的排序数组,并且不再需要这个答案
迭代 angularFire 对象中的值的正确方法是使用 $getIndex()。您在上面的代码中有这个,但没有在 for 循环中使用它。
由于您已经在使用AngularFire 库(syncData 是使用AngularFire 的 AngularFire 种子服务),因此无需担心调用 $apply() 或将数据导入 Angular 的任何其他复杂性,详见前面的答案(这对于原始 Firebase/Angular 实现来说是一个很好的回应)。
相反,只需更改 for 循环来迭代键而不是 angularFire 实例:
syncData('everyone').$bind($scope, 'everyone').then(function() {
var keys = $scope.everyone.$getIndex();
// utilizing Angular's helpers
angular.forEach(keys, function(key) {
console.log(key, $scope.everyone[key]);
});
// or as a for loop
for(var i=0, len = keys.length; i < len; i++) {
console.log(keys[i], $scope.everyone[keys[i]]);
}
});
Run Code Online (Sandbox Code Playgroud)
要利用 DOM 中的对象,请使用ng-repeat:
<ul>
<li ng-repeat="(key,user) in everyone">{{key}}, {{user|json}}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7237 次 |
| 最近记录: |