使用AngularFire创建初始​​数据

时间:2013-09-18 12:55:04

标签: angularjs firebase angularfire

我正在使用AngularJS和Firebase创建一个webapp,以便同时学习它们。

我在firebase(activitylog)中有一些用户活动数据,新用户不会存在这些数据。在添加活动数据的控制器中,我无法确定创建新用户条目以记录新数据的最佳方法。我有以下内容,似乎必须有更好的方法,因为它会导致一个以前从未使用过的“虚拟”条目。我的firebase被安排成使得活动日志是用户id的孩子,例如,火力/ activitylog / [用户id] / [activityId] / [activityEntry]。它不一定是这种方式,似乎是目前组织它的最佳方式。 (注意我有一个工厂,根据FireFeed RSS开源项目处理名为fbRef的firebase引用)。如果调用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 个答案:

答案 0 :(得分:0)

您可以更新到最新版本的AngularFire(此时为0.3),可在https://cdn.firebase.com/libs/angularfire/0.3.0/angularfire.js处获得 - 在此版本中,绑定到不存在的数据将起作用,并且不需要第4个参数。例如:

var ref = new Firebase(URL);
$scope.remote = {};
angularFire(ref, $scope, "remote");
即使URL上没有数据,

也能正常工作。