Pregunta

I'm trying to bind to a primitive with angularfire. Here's how I"m doing it:

      $firebase(fb.child('counts/node')).$on('value', function (obj) {
        $scope.nodeCount = obj.snapshot.value
      })

Is this correct? This API seems very different from the rest of firebase. I expected to get an ss as callback and do ss.val() but that doesn't seem to be the case. Can someone confirm if this is how it's supposed to be or if I'm doing it wrong. Thanks.

¿Fue útil?

Solución

Generally, as outlined in the getting started guide and API, you should simply be accessing the data directly in the view:

// javascript
$scope.messages = $firebase(new Firebase(URL));

<!-- html -->
<li ng-repeat="message in messages">{{message}}</li>

If you want to iterate the data in a controller (bad) or service (better), you can read the keys in the order as the database by using $getIndex().

// javascript
var ref = $firebase(new Firebase(URL));
ref.$on('loaded', function() {
   angular.forEach(ref.$getIndex(), function(key) {
      console.log('the next message is', key, ref[key]);
   });
});

If you are, in fact, trying to synchronize a single primitive value, angularFire is hardly necessary:

$scope.primitive = null;
var ref = new Firebase(URL);
ref.on('value', function(snap) { $scope.primitive = snap.val(); });

$scope.saveValue = function(newValue) {
   ref.set(newValue);
};

But certainly possible:

// javascript
$scope.primitive = $firebase(new Firebase(URL));

<!-- html -->
<input ng-model="primitive.$value" />

All of this is covered in the above links, which should be treated as required reading before getting started with Angular + Firebase.

changes in 0.8

angularFire 0.8 will be out soon. It will change this structure a little bit, utilizing a $asArray(), $asObject(), and also providing a .then() method, so a bit more like this:

// javascript
var ref = $firebase(new Firebase(URL));
$scope.messages = ref.$asArray();

$scope.ref.then(function() {
   angular.forEach($scope.messages, function(message) {
      console.log('the next message is', message.$id);
   });
});

<!-- html -->
<li ng-repeat="message in messages">{{message}}</li>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top