簡體   English   中英

Ember.js在模板中顯示hasMany數據,其中包含一個或多個結果

[英]Ember.js show hasMany data in template with one or more results

經過無盡的嘗試,我希望有人能找到我正在嘗試的線索。 我知道有關stackoverflow的這個特定主題有很多問題。 但是我想我不會問同樣的問題。 因為我沒有找到我的具體挑戰的答案。

這是我的路由器

App.Router.map(function () {
    this.resource('article', {path: '/article/:id'});
    this.resource('article.new', {path: "/article/new"});
});

路線

App.ArticleRoute = Ember.Route.extend({
    model: function (params) {
        return this.store.find('article', params.id);
    }
});

App.ArticleNewRoute = Ember.Route.extend({
    renderTemplate: function () {
        this.render('article', {
            controller: 'article.new'
        });
    },
    model: function () {
        return this.store.createRecord('article');
    }
});

模特

App.Category = DS.Model.extend({
    name: DS.attr('string'),
    image: DS.attr('string'),
    categoryRelation: DS.belongsTo('category')
});

App.Article = DS.Model.extend({
    name: DS.attr('string'),
    category: DS.hasMany('category')
)};

從服務器返回的JSON

{
   "articles":[
      {
         "id":1,
         "name":"Car 1",
         "category":[1,2],
      {
         "id":2,
         "name":"Car 2",
         "category":2,
   ],

   "categorys":[ // note the added 's' when returning multiple items as per EmberJS convention
      {
         "id":1,
         "name":"Oldtimers"
      },
      {
         "id":2,
         "name":"Classic"
      }
   ],
}

現在問題是,因為我在我的模板中嘗試以下內容:

<script type="text/x-handlebars" data-template-name="article"> 
    <div>
        {{#each category in model}}
            {{category.name}}<br>
            {{name}}<br>
        {{/each}}
    </div>
</script>

我在模板中嘗試了多種變體,這是我最后的代碼,看起來是正確的。 注意:對於ID為2的文章,如果只有一篇文章,模板也必須呈現。

編輯:我為你們翻譯了一些代碼。 如果有拼寫錯誤,則可能不在原始代碼中。

您的文章模板只會收到一篇文章,因此這個{{#each category in model}}不起作用,您需要使用{{#each category in model.category}}

<div>
    Article {{name}}<br/>
    {{#each category in model.category}}
        Category {{category.name}}<br/>            
    {{/each}}
</div>

這是行動中的一個小提琴http://jsfiddle.net/marciojunior/fj26R/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM