Firebase 回调和 AngularJS

问题描述:

我正在结合 Firebase 学习 AngularJS.我真的很纠结于 Firebase 的 on 回调,并试图更新 $scope...

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});   
    };
});

如果我将 $rootscope.$apply 取出,那么它会按预期工作,但不会在页面加载时更新 DOM.

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

谢谢!

更新

解决方案 1 - 删除服务上的 $rootscope.$apply 并将 $timeout 注入和应用到控制器:

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);
});

解决方案 2 - 实施SafeApply"方法(感谢 Alex Vanston):

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);
        }
    };

虽然这些都有效并且代码不多,但我觉得它们太hacky了.是否有一些官方的 Angular 方式来处理异步回调?

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?

我为类似情况找到的另一个很好的例子:HTML5Rocks - AngularJS 和 Socket.io

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

Solution 1 - 移除服务上的 $rootscope.$apply 并注入 $timeout 并将其应用到控制器:

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);
});

解决方案 2 - 实施SafeApply"方法(感谢 Alex Vanston):

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);
        }
    };