im new using angular and firebase and I am trying to make a controller to get data from database, and then send it into the scope and then in the html use the ng-repeat, this is my code:
var todoApp = angular.module('todoApp', ['todoApp.controllers','ui.router','firebase']);
todoApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'templates/home.html'
});
});
var todoControllers = angular.module('todoApp.controllers', ['firebase']);
todoControllers.controller('homeCtrl',function($scope){
db.ref("imagenes").on('value', function (snapshot) {
//asignamos a la variable del controlador
$scope.imagenes = snapshot.val();
console.log('inside: ' +$scope.imagenes);
});
console.log('outside: '+$scope.imagenes);
});
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.6.6/firebase.js"></script>
<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script>
in this example, i'm using console.log to see what I recieve, when it is 'inside: ' It works, it print the data I have on the database, but when it is 'outside: ' it prints undefined, so in the html it is undefined too.
Can you please help me! Thanks!
Angular's change detection isn't triggered when $scope is set inside Firebase's on('value', [callback])
event. You can solve this by wrapping your code setting the $scope variable with $scope.$apply
, like this:
db.ref("imagenes").on('value', function (snapshot) {
//asignamos a la variable del controlador
$scope.$apply(function(){
$scope.imagenes = snapshot.val();
});
});
Also note, if you aren't aware of it, that using .on('value', [callback])
actually registers an event listener, so every time the referenced object is changed in Firebase (or any child object), your callback is called. This might be intentional, but if you only want your data to retrieved one time, you should use once('value', [callback])
instead.
Also, if you're using a more recent version of Firebase (within the last year I believe), you can use promises instead of callbacks. That allows you to use $q.$when
to have angular trigger a digest, instead of $scope.apply
. In order to do that, you would change your code to this:
$q.$when(db.ref("imagenes").on('value').then(function (snapshot) {
//asignamos a la variable del controlador
$scope.imagenes = snapshot.val();
}));