如何使用最新的angularfire和fire util加入firebase数据?

时间:2014-12-04 21:47:23

标签: firebase

我有一个类别列表和产品列表:

{
  categories: {
    'myCategoryId': {
        name: 'my category name',
        products: {
            'first': true,
            'second': true
        }
    }
  },
  products: {
    'first': {
        name: 'my product name',
        categoryId: 'myCategoryId'
    },
    'second': {
        name: 'my second product name',
        categoryId: 'myCategoryId'
    }
  }
}

在我的侧边栏中,我想显示一个带有产品名称的类别的联合列表,因此我需要一些连接结构,如:

{
  categoriesWithNames: {
    'myCategoryId': {
        name: 'my category name',
        products: {
            'first': {
                name: 'my product name'
            },
            'second': {
                name: 'my second product name'
            },
        }
    }
  }

我知道我可以使用Firebase util和AngularFire来做到这一点,但是我尝试了几种不同的方法,我无法理解在Firebase中加入非规范化数据的概念。任何人都可以帮助我吗?

代码

var myApp = angular.module("myApp", ["firebase"]);
var FBURL = "MYFBURL";
var FBEVENTS = {
    'deleted':'child_removed',
    'added':'child_added'
};

myApp.controller('MyController', ['$scope', '$firebase',
    function ($scope, $firebase){

        var base = fb(FBURL);

        function fb(url) {
            return new Firebase(url);
        }

        function fbChild(attrs) {
            return $firebase(typeof attrs === "string" ? base.child(attrs) : base.child(attrs.join("/")));
        }

        function $a(fbChild) {
            return fbChild.$asArray();
        }

        function $o(fbChild) {
            return fbChild.$asObject();
        }

        var products = fbChild('products');
        var categories = fbChild('categories');

        $scope.products = $a(products);
        $scope.categories = $a(categories);

        $scope.products.$loaded().then(function(){
            $scope.categories.$watch(function (snapshot) {
                console.log('snapshot is', snapshot);
                if(snapshot.event!==FBEVENTS.deleted) {
                    var foundCat = $scope.categories.$getRecord(snapshot.key);
                    foundCat.products = _.map(foundCat.products, function (val, key){
                        if (val !== true)
                            return val;
                        return $scope.products.$getRecord(key);
                    });
                }
            });
        });
    }

0 个答案:

没有答案