4

我正在结合 Firebase 学习 AngularJS。我真的在on努力应对 Firebase 的回调并尝试更新$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

4

1 回答 1

8

解决方案 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);
        }
    };
于 2012-10-26T08:30:52.233 回答