代码之家  ›  专栏  ›  技术社区  ›  Michael J. Calkins

firebase-对对象使用一个ref并将其推到其子数组上

  •  1
  • Michael J. Calkins  · 技术社区  · 11 年前

    这段代码可以工作,但是我使用两个ref访问同一对象的不同区域。

    一个例程可能有多个页面。有没有一种方法可以创建新页面,只需使用一个ref将页面推送到$scope.routine.pages上,同时创建一个唯一的id?

    enter image description here

    angular.module('screenTester.auth.routine', [
        'screenTester.auth.routine.page'    
    ])
    
    .config(['$stateProvider', function($stateProvider) {
    
        $stateProvider
            .state('auth.routine', {
                url: '/routine/:routineId',
                controller: 'RoutineCtrl',
                templateUrl: '/dist/auth/routine/routine.html'
            });
    
    }])
    
    .controller('RoutineCtrl', ['$scope', '$stateParams', '$firebase', function($scope, $stateParams, $firebase) {
    
        $scope.routineId = $stateParams.routineId;
    
        // Combine these two and still create pages with a unique id?
        var ref = new Firebase("https://url.firebaseio.com/user" + $scope.auth.user.id + '/routines/' + $scope.routineId);
        var sync = $firebase(ref);
    
        var ref = new Firebase("https://url.firebaseio.com/user" + $scope.auth.user.id + '/routines/' + $scope.routineId + '/pages');
        var pagesSync = $firebase(ref);
    
        $scope.createPage = function() {
            // What method would I use here on `$scope.routine`?        
            $scope.routinePages.$add($scope.newPage);
            $scope.routinePages.$save();
            $scope.newPage = {};
            $scope.toggles.showCreatePage = false;
        };
    
        $scope.init = function() {
          $scope.routine = sync.$asObject();
          $scope.routinePages = pagesSync.$asArray();
    
          $scope.newPage = {};
          $scope.toggles = {};
        };
    
        $scope.init();
    
    }]);
    

    免责声明:不是我的最终代码,我正在学习firebase的工作原理,看看它是否是一个好的解决方案。

    1 回复  |  直到 11 年前
        1
  •  1
  •   webduvet    11 年前

    我认为使用多重引用在任何方面都不是问题。到服务器的连接只有一个。

    但是,如果您想重用该实例,可以尝试执行以下操作:

    var ref = new Firebase("https://url.firebaseio.com/user" + $scope.auth.user.id + '/routines/' + $scope.routineId);
    
    var sync = $firebase(ref);
    
    var pagesSync = $firebase(ref.child('pages'));
    

    这是 documentation 我指的是。