Firebase回调和AngularJS

时间:2012-10-25 09:17:44

标签: angularjs firebase

我正在与Firebase一起学习AngularJS。我正在努力解决Firebase的on回调并尝试更新$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。

谢谢!

更新

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

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

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

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

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

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

1 个答案:

答案 0 :(得分:8)

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

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

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

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