问题
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
I am trying to access the "Completed" element with value 339. However, console.log(data['Completed'])
returns undefined. What is wrong?
回答1:
A $firebaseObject
starts out as an empty object, but when the data has been downloaded from the Firebase database, it then populates the object.
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.
So you're probably asking, How do I handle the data if it doesn't exist at first?
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.
Your controller would look like this:
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
}
来源:https://stackoverflow.com/questions/34932687/how-to-navigate-object-returned-from-angularfire