Pablo DelaNoche Pablo DelaNoche - 4 months ago 27
AngularJS Question

firebase loading $scope view enter doesn't load

I have a loading problem in Firebase. I want to display a list of images when I open the view but nothing happens till i go back ( there is a flash and i can see my photo list). It's working but not displaying in the opening.

What am i missing please ?

There is the beginning of my Controller view

'Use Strict';
angular.module('App').controller('valider_photosController', function($scope, $state, $localStorage, Popup, Firebase, $firebaseObject, $ionicHistory, $ionicPopup, $ionicModal, $cordovaCamera) {
$scope.imagestab = [];
var ref_logements = firebase.database().ref('logements');
var ref_images = firebase.database().ref('images');

ref_logements.child(id_logement).child('images').on('child_added', added);

function added(idxSnap, prevId){
ref_images.child(idxSnap.key).once('value', function(datasnap){
var bidule = datasnap.val();
bidule['key'] = datasnap.key;
$scope.imagestab.push(bidule);
console.log('La valeur'+datasnap.key+'donne '+datasnap.val());
});
};

Answer

Since firebase works with asynchronous calls, by the time firebase responds with your data the angular cycle had already finished and you won't have your scope updated. You can force it by using $scope.$apply();.

ref_images.child(idxSnap.key).once('value', function(datasnap){
      var bidule = datasnap.val();
      bidule['key'] = datasnap.key;
      $scope.imagestab.push(bidule);
      $scope.$apply();
});

There is a tool that integrates angular and firebase in a way that you won't have to be concerned with things such as applying the scope. Its called angularfire. I totally recommend you to start using it in your application.

With angularfire you can get your data simply using

$scope.bidule = $firebaseObject(ref_images.child(idxSnap.key));

or

$scope.images = $firebaseArray(firebase.database().ref('images'));
Comments