简体   繁体   中英

ionic 1 with Firebase 3 get key from snapshot?

firebase.database().ref('users/' + user.uid + '/cars')

 .on('value', function(snapshot) {
    $scope.cars = snapshot.val();
    console.log('snapshot', JSON.stringify(snapshot.val()));
  });

I can pull all the data I need except, for the key value set by Firebase ( -KVChuDgmbogzH2bKm1A ). It is being logged to the console. But I can't display it. I have tried cars.key, key, $id, cars.$id

<div ng-repeat="car in cars">     

 <p>item key: {{car.key}}</p> <- this I can't get 
        <h2>{{car.color}}</h2><- this is fine
         <p>{{car.motor}}</p><-  this is fine

Any advice would be greatly appreciated.

The data from Firebase is being loaded asynchronously. By the time the data is loaded, Angular isn't ready for it anymore.

So you need to tell AngularJS that it needs to update the HTML. The easiest way to do this is by wrapping the updating of the scope in a $timeout() call:

firebase.database().ref('users/' + user.uid + '/cars')    
 .on('value', function(snapshot) { $timeout() {
    $scope.cars = snapshot.val();
    console.log('snapshot', JSON.stringify(snapshot.val()));
 })});

Update

You seem to be looking for the key of each snapshot.

<div ng-repeat="(key, car) in cars">     

 <p>item key: {{key}}</p> <- this I can't get 
    <h2>{{car.color}}</h2><- this is fine
     <p>{{car.motor}}</p><-  this is fine

At this point I recommend switching to using AngularFire, which solves many problems for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM