代码之家  ›  专栏  ›  技术社区  ›  Alex Benke

使用AngularFire创建初始数据

  •  1
  • Alex Benke  · 技术社区  · 12 年前

    我正在使用AngularJS和Firebase创建一个网络应用程序,以便学习两者。

    我在firebase(activitylog)中有一些用户活动数据,这些数据对于新用户来说是不存在的。在添加活动数据的控制器中,我很难找到创建新用户条目以记录新数据的最佳方法。我有以下内容,似乎肯定有更好的方法,因为它会产生一个以后永远不会使用的“伪”条目。我的firebase被安排为活动日志是用户id的子级,例如firebase/activitylog/[userid]/[activityId]/[activity Entry]。不一定非得这样,只是现在看来这是最好的组织方式。(注意,根据FireFeed RSS开源项目,我有一个处理firebase引用的工厂,名为fbRef)。如果调用angularFire()只是在引用不存在的东西时创建一个记录,那就太好了,但它只会给出一个错误。任何帮助都将不胜感激。

    .controller('ActivityLogCtrl', ['$scope', '$location', '$routeParams', '$timeout', 'angularFireCollection', 'angularFire', 'fbRef', function($scope, $location, $routeParams, $timeout, angularFireCollection, angularFire, fbRef) {
    
      //check if the user has a activitylog entry from the past, if not create a default one
      var ref = fbRef(['activitylog', $scope.user.id]);
    
      ref.on('value', function(snapshot) {
        if(snapshot.val() === null) {
            var wlref = fbRef(['activitylog']);
            // create a new dummy entry
            wlref.child($scope.user.id).set('initial');
        }
      });
    
      // now I know if have an entry, use it.
      angularFire(fbRef(['activitylog', $scope.user.id]), $scope, 'remote', {}).
      then(function() {
    
        $scope.activitylog = angular.copy($scope.remote);
    
        ...
    
    1 回复  |  直到 12 年前
        1
  •  0
  •   Anant    12 年前

    您可以更新到AngularFire的最新版本(目前为0.3),可在 https://cdn.firebase.com/libs/angularfire/0.3.0/angularfire.js -在这个版本中,绑定到不存在的数据就可以了,不需要第四个参数。例如:

    var ref = new Firebase(URL);
    $scope.remote = {};
    angularFire(ref, $scope, "remote");
    

    即使URL中没有数据,也能正常工作。

    推荐文章