Firebase回调和AngularJS

前端之家收集整理的这篇文章主要介绍了Firebase回调和AngularJS前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在和Firebase一起学习AngularJS.我正在努力解决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 out然后它按预期工作但它不会在页面加载时更新DOM.

谢谢!

UPDATE

解决方案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);
        }
    };

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

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

解决方法

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

firebaseService.on('child_added',0);
});

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

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

猜你在找的Angularjs相关文章