Firebase回调和AngularJS

Max*_*lmo 4 angularjs firebase

我正在和Firebase一起学习AngularJS.我真的很挣扎onFirebase 的回调,并试图更新$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});   
    };
});
Run Code Online (Sandbox Code Playgroud)

如果我$rootscope.$apply拿出它然后它按预期工作但它不会在页面加载时更新DOM.

谢谢!

UPDATE

解决方案1 ​​ - 删除$rootscope.$apply服务并注入并应用于$timeout控制器:

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

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

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

虽然这些都起作用并且代码不多,但我觉得它们太过于hacky.是不是有一些正式的Angular方式来处理异步回调?

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

Max*_*lmo 8

解决方案1 ​​ - 删除$ rootscope.$ apply on the service并注入并将$ timeout应用于控制器:

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

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

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