Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase callbacks and AngularJS

I am learning AngularJS in conjunction with Firebase. I am really struggling with the on callback of Firebase and trying to update the $scope...

$apply already in progress <----

    var chat = angular.module('chat', []);
   chat.factory('firebaseService', function ($rootScope) {
  var firebase = {};
  firebase = new Firebase("http://gamma.firebase.com/myUser");
  return {
    on: function (eventName, callback) {
      firebase.on(eventName, function () {  
        var args = arguments;
        $rootScope.$apply(function () {
          callback.apply(firebase, args);
        });
      });
    },
    add: function (data) {
      firebase.set(data);
    }
  };
});

chat.controller ('chat', function ($scope, firebaseService) {
    $scope.messages = [];
    $scope.username;
    $scope.usermessage;              
    firebaseService.on("child_added",function(data){        
        $scope.messages.push(data.val());       
    });
    $scope.PushMessage = function(){
        firebaseService.add({'username':$scope.username,'usermessage':$scope.usermessage});   
    };
});

If I take the $rootscope.$apply out then it works as expected but it doesn't update the DOM on page load.

Thanks!

UPDATE

Solution 1 - Remove the $rootscope.$apply on the service and inject and apply the $timeout to the controller:

firebaseService.on('child_added',function(data){        
    $timeout(function(){
        $scope.messages.push(data.val());                       
    },0);
});

Solution 2 - Implement a "SafeApply" method (thanks to Alex Vanston):

$scope.safeApply = function(fn) {
        var phase = this.$root.$$phase;
        if(phase == '$apply' || phase == '$digest') {
            fn();
        } else {
            this.$apply(fn);
        }
    };

Although these both work and are not much code I feel they are too hacky. Isn't there some offical Angular manner in which to handle Async callbacks?

Another great example I found for a similar situation: HTML5Rocks - AngularJS and Socket.io

like image 863
MaxWillmott Avatar asked Feb 18 '23 17:02

MaxWillmott


1 Answers

Solution 1 - Remove the $rootscope.$apply on the service and inject and apply the $timeout to the controller:

firebaseService.on('child_added',function(data){        
    $timeout(function(){
        $scope.messages.push(data.val());                       
    },0);
});

Solution 2 - Implement a "SafeApply" method (thanks to Alex Vanston):

$scope.safeApply = function(fn) {
        var phase = this.$root.$$phase;
        if(phase == '$apply' || phase == '$digest') {
            fn();
        } else {
            this.$apply(fn);
        }
    };
like image 192
MaxWillmott Avatar answered Jun 04 '23 12:06

MaxWillmott