【问题标题】:AngularFire Loop denormalized dataAngularFire Loop 非规范化数据
【发布时间】:2014-02-07 16:57:19
【问题描述】:

我有类别和子类别。

数据结构如blog所示:

categories: {
    -JF1RmYehtF3IoGN9xHG(categoryId): {
      title: "Example",
      subcategories: {
        JF1RmYehtF3IoGN239GJ(subCategoryId): true
      }

到目前为止,我以这种方式检索数据(仅针对一个类别):[控制器]

$scope.findOneCategory = function (categoryId) {
    angularFire(Categories.find(categoryId), $scope, 'category');
}

分类服务

      find: function(categoryId) {
        return FireRef.categories().child('/'+categoryId);
      },

这很好用!

但现在我需要检索类别中的子类别列表并将其绑定到范围,我不知道如何...我目前有这个:

观点:

<div ng-init="findSubCategories()">
<li class="list-group-item" ng-repeat="subCategory in subCategories">{{ subCategory.name }}</li>

控制器:

    $scope.findSubCategories = function() {
      angularFire(Categories.findSubCategories($routeParams.categoryId), $scope, 'subCategories');
    }

服务看起来像这样

      findSubCategories: function(categoryId) {

        var subCategoriesIdsList = FireRef.categories().child('/'+categoryId).child('subcategories');

        subCategoriesIdsList.on("child_added", function(snap) {
              FireRef.subcategories().child("/"+snap.name()).once("value", function(snap) {
                // Render the comment on the link page.
                console.log(snap.val());(i see the object in console but have no idea how to bind it now with the view...:(
              });
        });

      },

不知道如何将其与角度视图绑定

【问题讨论】:

    标签: firebase angularfire


    【解决方案1】:

    首先,我建议升级到最新的 AngularFire 版本(当前为 0.6),API 已经发生了很大变化,它可能更容易完成你想要做的事情。

    其次,您应该只为每个类别创建一个绑定,并且子类别 ID 将自动包含在该数据中,因为它们只是子节点。然后,您需要为子类别名称创建一个单独的绑定,然后您可以查找您的 ID。

    假设您的数据如下所示:

    categories: {
      -JF1RmYehtF3IoGN9xHG: {
        title: "Example",
        subcategories: {
          JF1RmYehtF3IoGN239GJ: true
        }
      }
    },
    subCategories: {
      JF1RmYehtF3IoGN239GJ: {
        name: "Example Subcategory",
      }
    }
    

    您将创建两个绑定,一个用于类别,另一个用于子类别:

    function MyController($scope, $firebase) {
      var ref = new Firebase("https://<my-firebase>.firebaseio.com/");
      $scope.category = $firebase(ref.child("categories/" + categoryID));
      $scope.subcategories = $firebase(ref.child("subCategories"));
    }
    

    最后,在您看来,使用您从 $scope.category 中提取的 ID 从 $scope.subcategories 中获取子类别名称:

    <ul ng-repeat="(id, val) in category.subcategories">
      <li>{{subcategories[id].name}}</li>
    </ul>
    

    【讨论】:

    • 当这不是类别和子类别,而是帖子和用户并且您想显示单个用户的帖子列表时,这是否是正确的解决方案?可能有很多帖子和很多用户。我尝试了许多不同的方法来做到这一点,但似乎找不到合适的方法。
    • 如果子类别列表真的很长,那么加载它可能没有意义。在这种情况下,我会通过为每个子类别创建一个新的 $firebase 实例来一个一个地获取它们(或者可能只是使用常规的 Firebase API)。
    猜你喜欢
    • 2014-04-19
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 2010-10-06
    • 1970-01-01
    • 2013-12-11
    • 2013-01-18
    相关资源
    最近更新 更多