Ember:从多个相关模型渲染嵌套循环

时间:2014-11-05 02:24:11

标签: ember.js

我无法渲染以下嵌套循环:

<script type="text/x-handlebars" id="chapters">
  <h4>Chapters</h4> 
  <ul>  
    {{#each chapter.book}}
      <li>
        {{book.name}}
          {{#each}}
            <li>
              {{name}}
            </li>
          {{/each}}  
      </li>
    {{/each}}
  </ul>
</script>

我想要完成的是遍历所有书籍,并为每本书循环阅读其章节。该模型返回所有​​章节。我怀疑我的Handlebars模板语法不正确。

以下问题很有帮助,但它没有解决我的问题: How to use multiple models with a single route in EmberJS / Ember Data?

问题中的两个模型是:

App.Book = DS.Model.extend({
  name: DS.attr('string'),
  icon: DS.attr('string'),
  description: DS.attr('string'),
  createdDate: DS.attr('date'),
  chapters: DS.hasMany('chapter', { inverse: 'book', async: true}),
  bookAssignments: DS.hasMany('bookAssignment', {async: true}),
  user: DS.belongsTo('user', { inverse: 'books', async: true} ),
});

App.Chapter = DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  unit: DS.attr('string'),
  dashboard: DS.attr('boolean'),
  createdDate: DS.attr('date'),
  source: DS.attr('string'),
  book: DS.belongsTo('book', { inverse: 'chapters', async: true}),
  user: DS.belongsTo('user', { inverse: 'chapters', async: true} )
});

路线:

App.ChaptersRoute = Ember.Route.extend({
  model: function() {
    return this.store.findAll('chapter');
  },
});  

提前致谢。

1 个答案:

答案 0 :(得分:1)

在你的情况下,你想要获得所有独特的书籍,并迭代它们。有了章节控制器,它就是这样的:

App.ChaptersController = Ember.ArrayController.extend({
  //content because they are promises
  books: Ember.computed.mapBy('model', 'book.content'),
  uniqueBooks: Ember.computed.uniq('books'),
});

模板(我添加了另一个UL)

<script type="text/x-handlebars" id="chapters">
  <h4>Chapters</h4> 
  <ul>  
    {{#each book in uniqueBooks}}
      <li>
        <ul>
        {{book.name}}
          {{#each chapter in book.chapters}}
            <li>
              {{chapter.name}}
            </li>
          {{/each}} 
        </ul> 
      </li>
    {{/each}}
  </ul>
</script>

唯一的示例:http://emberjs.jsbin.com/vuhaga/3/edit?html,js,output