如何浏览从AngularFire返回的对象? [英] How to navigate object returned from AngularFire?
问题描述
当我运行下面的火力地堡查询:
When I run the following Firebase query:
var ref = new Firebase('https://<myfirebase>.firebaseio.com/companies/endo/status');
data = $firebaseObject(ref);
console.dir(data);
我得到以下对象:
I get the following object:
d
$$conf: Object
$id: "status"
$priority: null
Active, not recruiting: 39
Approved for marketing: 1
Completed: 339
Enrolling by invitation: 10
Not yet recruiting: 23
Recruiting: 128
Suspended: 3
Terminated: 38
Unknown: 74
Withdrawn: 15
__proto__: Object
我想用价值339但是,的console.log进入已完成的元素(数据['完成'])
返回undefined。什么是错的?
I am trying to access the "Completed" element with value 339. However, console.log(data['Completed'])
returns undefined. What is wrong?
推荐答案
A $ firebaseObject
开始作为一个空的对象,但是当数据已经从火力地堡下载数据库中,然后填充的对象。
A $firebaseObject
starts out as an empty object, but when the data has been downloaded from the Firebase database, it then populates the object.
起初,你看不到任何东西,因为数据还没有下载。你的的console.log()
运行 $ firebaseObject
创建后十亿分之一秒。该数据后下载毫秒。
At first, you don't see anything because the data hasn't downloaded yet. Your console.log()
runs a nanosecond after the $firebaseObject
is created. The data is downloaded milliseconds after.
所以,你可能会问,如何处理数据,如果不首先存在吗?
你可以做的是附加 $ firebaseObject
到 $范围
。然后在你的模板绑定。当数据下载角 $消化
循环运行,并刷新您的模板。
What you can do is attach the $firebaseObject
to $scope
. And then bind it in your template. When the data downloads the Angular $digest
loop runs, and refreshes your template.
您的控制器是这样的:
app.controller('MyCtrl', function($scope, $firebaseObject) {
var ref = new Firebase('https://<myfirebase>.firebaseio.com/companies/endo/status');
$scope.data = $firebaseObject(ref);
});
您的模板应该是这样的:
Your template would look like this:
<div>Did you do it? {{ data.Completed }}</div>
还有另外一种方法,这需要多一点的设置,但它是我个人最喜欢的。您还可以使用路由器将数据解析到控制器中。
There is another way, which takes a bit more setup, but it's my personal favorite. You can also use the router to resolve the data into the controller.
angular.module('app', ['firebase'])
.constant('FirebaseUrl', '<my-firebase-app>')
.service('rootRef', ['FirebaseUrl', Firebase])
.controller('MyCtrl', MyController)
.config(ApplicationConfig);
function ApplicationConfig($routeProvider) {
$routeProvider.when('/', {
controller: 'MyCtrl',
template: 'view.html',
resolve: {
data: function ($firebaseObject, rootRef) {
var ref = rootRef.child('companies/endo/status');
// a promise for the downloaded data
return $firebaseObject(ref).$loaded();
}
}
});
}
function MyController($scope, data) {
$scope.data = data;
console.log(data.Completed); // will work because the data is downloaded
}
这篇关于如何浏览从AngularFire返回的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!