2015-10-04 53 views
1

我是新來的流星,但獲得了一些這個框架的公平知識。我創建一個應用程序中,我必須建立一個分類管理模塊,我使用的是分類收集,這和在文檔中我的價值觀就是這樣流星類別和子類別選擇菜單

{ 
_id: 
name: 
parentID: 

..... 
} 

我已經試過幾件事情,使之遞歸,但沒有做到這一點,我需要的是一個包含所有類別與子女的下拉菜單。像這樣:

http://blog.digibali.com/wp-content/uploads/2011/03/menutree2.jpg

我希望如果有人在這裏可以在這個問題上需要幫助:

現在我在做什麼是取我只有2級,我的意思是最高父和子子,我想這個無限的水平,我知道這可能是通過遞歸函數是可能的,但無法找到路

模板:

<template name="categoryselect"> 

<select id="category" name="category" class="category"> 
<option value="">--Select--</option> 
{{#each get_categories}} 
<option value="{{_id}}">{{name}}</option> 
{{#each get_sub_categories}} 
{{> subcategoryselect}} 
{{/each}} 
{{/each}} 

</select> 

</template> 


<template name="subcategoryselect"> 
<option value="{{_id}}">--{{name}}</option> 
</template> 

名模板助手:

Template.categoryselect.helpers({ 
'get_categories': function(){ 
return Categories.find({parentID:''}); 

}, 

'get_sub_categories': function(){ 
return Categories.find({parentID:this._id}); 
} 

}); 

回答

2

這裏有一個測試的解決方案:

HTML

<template name="categoryselect"> 
    <select id="category" name="category" class="category"> 
    <option value="">--Select--</option> 
    {{#each get_categories}} 
     <option value="{{_id}}">{{name}}</option> 
    {{/each}} 
    </select> 
</template> 

JS

Template.categoryselect.helpers({ 
    get_categories: function() { 
    var results = []; 

    var mapChildren = function(category, level) { 
     // add the appropriate number of dashes before each name 
     var prefix = Array(2 * level).join('--'); 
     results.push({_id: category._id, name: prefix + category.name}); 

     // repeat for each child category 
     var children = Categories.find({parentID: category._id}).fetch(); 
     _.each(children, function(c) { 
     // make sure to increment the level for the correct prefix 
     mapChildren(c, level + 1); 
     }); 
    }; 

    // map each of the root categories - I'm unsure if the parent 
    // selector is correct or if it should be {parentId: {$exists: false}} 
    _.each(Categories.find({parentID: ''}).fetch(), function(c) { 
     mapChildren(c, 0); 
    }); 

    // results should be an array of objects like {_id: String, name: String} 
    return results; 
    } 
}); 
+0

嗨大衛,這就是我一直在尋找:)謝謝你的幫助LP,它也給了我一些洞察力,看看Underscore.JS助手;) – Manu