英文原文:http://emberjs.com/guides/controllers/representing-multiple-models-with-arraycontroller/

代表多模型(Representing Multiple Models)

You can use Ember.ArrayController to represent an array of models. To tell an ArrayController which model to represent, set its model property in your route’s setupController method.

Ember.ArrayController用于代表一组模型。通过在路由的setupController方法中设置ArrayControllermodel属性,来指定其代表的模型。

You can treat an ArrayController just like its underlying array. For example, imagine we want to display the current playlist. In our router, we setup our SongsController to represent the songs in the playlist:

可以将ArrayController作为一个数组来对待。例如,音乐播放器希望显示当前播放列表。在路由中,通过设置SongsController来代表播放列表中的歌曲。

  1. App.SongsRoute = Ember.Route.extend({
  2. setupController: function(controller, playlist) {
  3. controller.set('model', playlist.get('songs'));
  4. }
  5. });

In the songs template, we can use the {{#each}} helper to display each song:

songs模板中,可以使用{{#each}}助手来显示歌曲。

  1. <h1>Playlist</h1>
  2. <ul>
  3. {{#each}}
  4. <li>{{name}} by {{artist}}</li>
  5. {{/each}}
  6. </ul>

You can use the ArrayController to collect aggregate information about the models it represents. For example, imagine we want to display the number of songs that are over 30 seconds long. We can add a new computed property called longSongCount to the controller:

另外,可以使用ArrayController来收集一些模型所代表的聚合类信息。例如,音乐播放器需要显示超过30秒长的歌曲的数量。那么只需要在控制器中添加一个名为longSongCount的计算属性。

  1. App.SongsController = Ember.ArrayController.extend({
  2. longSongCount: function() {
  3. var longSongs = this.filter(function(song) {
  4. return song.get('duration') > 30;
  5. });
  6. return longSongs.get('length');
  7. }.property('@each.duration')
  8. });

Now we can use this property in our template:

现在便可以在模板中使用该属性。

  1. <ul>
  2. {{#each}}
  3. <li>{{name}} by {{artist}}</li>
  4. {{/each}}
  5. </ul>
  6. {{longSongCount}} songs over 30 seconds.

Sorting

排序

The Ember.ArrayController uses the Ember.SortableMixin to allow sorting of content. There are two properties that can be set in order to set up sorting:

Ember.ArrayController使用Ember.SortableMixin来支持排序。为了支持排序,需要设置两个属性:

  1. App.SongsController = Ember.ArrayController.extend({
  2. sortProperties: ['name', 'artist'],
  3. sortAscending: true // false for descending
  4. });

Item Controller

条目控制器

It is often useful to specify a controller to decorate individual items in the ArrayController while iterating over them. This can be done in the ArrayController definition:

在遍历ArrayController的条目时,指定一个控制器来装饰单个条目非常有用。这可以在ArrayController中进行定义:

  1. App.SongsController = Ember.ArrayController.extend({
  2. itemController: 'song'
  3. });

or directly in the template:

或者在模板中指定:

  1. {{#each itemController="song"}}
  2. <li>{{name}} by {{artist}}</li>
  3. {{/each}}