2014-02-07 94 views
3

我有類別和子類別。AngularFire循環非規格化數據

數據的結構是一樣的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); 
     }, 

This works good!

但現在我需要檢索類別子類別列表,並將其綁定的範圍和我不知道如何......目前,我有這樣的:

的觀點:

<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...:(
       }); 
     }); 

     }, 

不知道如何與斜視結合本

回答

2

首先,我建議你升級到最新版本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> 
+0

當這不是類別和子類別,而是帖子和用戶,並且您想顯示單個用戶的帖子列表時,這是否是正確的解決方案?可能會有很多帖子和很多用戶。我嘗試了許多不同的方式來做到這一點,但似乎找不到合適的方法。 –

+0

如果子類別列表很長,那麼加載它可能沒有意義。在這種情況下,我會通過爲每個子類別創建一個新的$ firebase實例來逐個獲取它們(或者可能只是使用常規的Firebase API)。 – Anant