【问题标题】:Looping through model in unrelated template in ember在ember中循环遍历不相关模板中的模型
【发布时间】:2014-08-07 16:15:10
【问题描述】:

如果我在这里遗漏了一些关键概念,我深表歉意。我是 ember 的新手,我还没有从根本上“明白”。

在我正在开发的应用程序中,有一个侧边栏需要显示所有用户的相册,无论用户在哪个路线上。

在这个侧边栏模板中,我想做这样的事情,为每个专辑渲染一个专辑模板。

{{#each App.AlbumsController}}
  {{render "albums.album_link" this}
{{/each}}

edit:重要的是,我不希望专辑成为应用程序控制器的模型,因为我想在同一个侧边栏中至少再渲染一个模型并能够在它们之间切换。

基于Sort content of ArrayController 的建议(不确定 {{#view App.RecordView}} 发生了什么。这重要吗?)

我没有“专辑”路线,因为此侧边栏是唯一显示专辑索引的地方,它不需要自己的视图。

App.AlbumsController = Ember.ArrayController.extend({
  content: [],
  sortProperties: ['title'],
  sortAscending: false 
});   

当它被评估时,它在控制台中得到一个错误:未捕获的错误:断言失败:#each 循环的值必须是一个数组。你通过了 App.AlbumsController

我认为我的问题在于我不明白 arrayController 上的“内容”属性是做什么的,而且我可能没有正确设置它以将专辑对象加载到控制器中

我创建了一个垃圾箱,尝试循环侧边栏模板中的相册失败:http://jsbin.com/nufusa/9/edit

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    如果侧边栏内容在所有路由中都相同,最简单的方法是将相册定义为应用程序路由模型:

    # Route
    var App.ApplicationRoute = Em.Route.extend({
      model: function() {
        # Retrieve your albums, depending on where you store that data
      }
    })
    
    # Outernmost template (application.hbs)
    <div class="sidebar">
      {{#each}}
        {{render "albums.album_link" this}}
      {{/each}}
    </div>
    <div class="main">
      {{ outlet }}
    </div>
    

    如果不同的路线会有不同的侧边栏,请使用 outlets 来显示侧边栏。您可以像这样定位侧边栏插座:

    var App.SomeRoute = Ember.Route.extend({
      renderTemplate: function() {
        this.render();
        this.render('sidebar/something', {
          into: 'application',
          outlet: 'sidebar'
        });
      }
    });
    

    您可以在 ember 指南中找到有关在 outlet 中渲染模板的更多信息:http://emberjs.com/guides/routing/rendering-a-template/

    【讨论】:

    • 我现在意识到我不够具体并更新了问题。最终,我希望在该侧边栏中呈现多个模型,因此我想为每个模型提供自己的控制器并循环浏览侧边栏模板中的每个控制器
    • 您是指不止一种不同的型号,还是多张专辑?如果它是由几张专辑组成的数组——你将它设置为模型。如果您使用 Ember.Data,它将如下所示:this.store.find('album') -> 将检索所有专辑,this.store.find('album', 1) -> 将检索一个专辑(id:1)
    • 最终会在此模板中显示多个不同的模型,这就是为什么我不想为应用程序本身设置特定模型的原因我非常感谢您抽出时间回复!这迫使我在我的问题上更清楚。
    【解决方案2】:

    为了让它正确出来,而不是:

    App.AlbumsController = Ember.ArrayController.extend({
      content: [],
      sortProperties: ['title'],
      sortAscending: false 
    });  
    

    重要的是创建而不是在一行中扩展 ArrayController,然后单独设置它的属性。

    App.albumsController = Ember.ArrayController.create();
    
    App.albumsController.set('sortProperties', ['title']);
    App.albumsController.set('content', App.Album.FIXTURES);
    

    工作 js.bin:http://jsbin.com/nufusa/10/edit

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 2020-01-12
      • 2015-01-15
      相关资源
      最近更新 更多