6.2 Controllers -- Representing Multipe Models

1. 一个controller的model可以代表几个记录也可以代表单个。这里,路由的model hook返回一个歌曲数组:

app/routes/songs.js

export default Ember.Route.extend({
  model() {
    return this.store.findAll('song');
  }
});

songs的模板中,我们可以使用{{#each}}辅助器来展示每一首歌曲:

app/templates/songs.hbs

<h1>Playlist</h1>

<ul>
  {{#each model as |song|}}
    <li>{{song.name}} by {{song.artist}}</li>
  {{/each}}
</ul>

2. 你可以使用controller去收集model有关的集合信息。例如,想象一下我们希望展示长度超过30秒的歌曲的数量。我们可以为controller添加一个新的计算属性叫做longSongCount

app/controllers/songs.js

export default Ember.Controller.extend({
  longSongCount: Ember.computed('model.@each.duration', function() {
    let songs = this.get('model');
    let longSongs = songs.filter((song) => {
      return song.get('duration') > 30;
    });
    return longSongs.get('length');
  })
});

现在我们可以在模板中使用这个属性:

app/templates/songs.hbs

<ul>
  {{#each model as |song|}}
    <li>{{song.name}} by {{song.artist}}</li>
  {{/each}}
</ul>

{{longSongCount}} songs over 30 seconds.
原文地址:https://www.cnblogs.com/sunshineground/p/5165598.html